දත්ත එකතු
Array යනු එකම වර්ගයේ අයිතම (items) එකතුවක් ගබඩා කිරීමට භාවිතා කරන දත්ත ව්යුහයකි. TypeScript හි, array එකක ඇති සියලුම අයිතම කුමන වර්ගයේද යන්න අපට ප්රකාශ කළ හැක.
ව්යුහය (Syntax): let [variableName]: [type][] = [value1, value2, ...];
Tuple එකක් ද array එකක් මෙන් පෙනුනත්, එහි ප්රධාන වෙනස්කම් දෙකක් ඇත: 1) එහි ඇති අයිතම සංඛ්යාව ස්ථාවර වේ (fixed number of elements), 2) එක් එක් අයිතමයේ type එක වෙනස් විය හැකි අතර, එය නිර්වචනය කරන පිළිවෙලටම පැවතිය යුතුය.
Enum යනු එකිනෙකට සම්බන්ධ නියතයන් (constants) සමූහයකට හිතකාමී නම් (friendly names) ලබා දීමට ඇති ක්රමයකි. මෙමගින් අපගේ කේතය කියවීමට සහ තේරුම් ගැනීමට පහසු වේ. උදාහරණයක් ලෙස, 0, 1, 2 වෙනුවට ADMIN, READ_ONLY, AUTHOR ලෙස නම් භාවිතා කිරීම.
let numbers: number[] = [10, 20, 30, 40];
console.log(numbers[1]); // Accessing the second element20let fruits: string[] = ["Apple", "Banana", "Orange"];
fruits.push("Mango"); // Adding a new element
console.log(fruits);["Apple", "Banana", "Orange", "Mango"]`number` array එකකට `string` එකක් එකතු කිරීමට උත්සාහ කළ විට දෝෂයක් ඇතිවේ.
let scores: number[] = [100, 95, 88];
// The following line will cause a compilation error:
// Argument of type 'string' is not assignable to parameter of type 'number'.
// scores.push("Good");මෙහි පළමු අයිතමය `string` ද, දෙවැන්න `number` ද විය යුතුය.
// Declare a tuple type
let user: [string, number];
// Initialize it
user = ["Kamal", 25];
console.log(user);["Kamal", 25]let employee: [number, string] = [101, "Nimal"];
console.log(`Employee ID: ${employee[0]}`);
console.log(`Employee Name: ${employee[1]}`);Employee ID: 101Employee Name: NimalTuple එකක නිර්වචනය කළ type එකට වෙනස් අගයක් පැවරීමට උත්සාහ කිරීම.
let product: [string, number] = ["Book", 500];
// The following line will cause a compilation error:
// Type 'string' is not assignable to type 'number'.
// product[1] = "Five Hundred";Default ලෙස, enums 0 සිට ආරම්භ වන අංක ලබා දෙයි.
enum Role { ADMIN, READ_ONLY, AUTHOR };
let currentUser: Role = Role.ADMIN;
console.log(currentUser); // It will print the index0enum Role { ADMIN, READ_ONLY, AUTHOR };
let userRole: Role = Role.ADMIN;
if (userRole === Role.ADMIN) {
console.log("User is an administrator.");
}User is an administrator.අංක වෙනුවට, අපට අවශ්ය string අගයන් ද enum එකකට ලබා දිය හැක.
enum Direction {
UP = "UP",
DOWN = "DOWN",
LEFT = "LEFT",
RIGHT = "RIGHT"
}
let move: Direction = Direction.LEFT;
console.log(`Move direction: ${move}`);Move direction: LEFTArray එකකට විවිධ වර්ගයේ දත්ත ඇතුළත් කිරීමට අවශ්ය නම්, `any[]` භාවිතා කළ හැක.
let mixedArray: any[] = ["Hello", 123, true];
console.log(mixedArray);["Hello", 123, true]