මූලික දත්ත වර්ග
TypeScript හි ප්රධානතම ලක්ෂණය වන්නේ "types" ය. Variable එකක්, function parameter එකක්, හෝ object property එකක් කුමන වර්ගයේ දත්තයක් (උදා: වචනයක්, අංකයක්) රඳවා තබා ගන්නේද යන්න නිශ්චිතවම ප්රකාශ කිරීමට types අපට ඉඩ සලසයි. මෙය "type annotation" ලෙස හැඳින්වේ.
ව්යුහය (Syntax): let [variableName]: [type] = [value];
string: අක්ෂර, වචන, හෝ වාක්ය ගබඩා කිරීමට. උදා: "Hello World"number: පූර්ණ සංඛ්යා (integers) සහ දශම සංඛ්යා (floats) යන දෙවර්ගයම ගබඩා කිරීමට. උදා: 10, 3.14boolean: true (සත්ය) හෝ false (අසත්ය) යන අගයන් දෙක පමණක් ගබඩා කිරීමට.any: ඕනෑම වර්ගයක දත්තයක් ගබඩා කිරීමට ඉඩ දෙයි. Type checking එක මඟ හැරීමට අවශ්ය වූ විට මෙය භාවිතා කරයි. (නිතර භාවිතා කිරීම නිර්දේශ නොකරයි).let greeting: string = "Welcome to TypeScript!";
console.log(greeting);Integer සහ float යන දෙවර්ගයම සඳහා `number` type එක භාවිතා වේ.
let userId: number = 101;
let price: number = 499.99;
console.log(`User ID: ${userId}, Price: ${price}`);let isLoggedIn: boolean = true;
let hasErrors: boolean = false;
console.log(`Login Status: ${isLoggedIn}`);අපි type එකක් ලබා නොදුනහොත්, TypeScript විසින් variable එකට පවරන පළමු අගය අනුව එහි type එක අනුමාන කරයි.
// TypeScript infers that 'course' is of type 'string'
let course = "TypeScript";
// course = 123; // This will show an error!잘못된 type එකක අගයක් පැවරීමට උත්සාහ කළ විට TypeScript compiler එක මගින් දෝෂයක් (error) පෙන්වයි.
let age: number = 25;
// The following line will cause a compilation error:
// Type 'string' is not assignable to type 'number'.
// age = "twenty-five"; `any` ලෙස යෙදූ variable එකකට ඕනෑම වර්ගයක අගයක් පැවරිය හැක.
let myVariable: any = "This is a string";
console.log(myVariable);
myVariable = 100; // This is allowed
console.log(myVariable);function addNumbers(num1: number, num2: number) {
return num1 + num2;
}
// let result = addNumbers(10, "5"); // This will cause an error
let result = addNumbers(10, 5);
console.log(result);15Function එකකින් return කරන අගයේ type එක ද අපට නිශ්චිතවම ප්රකාශ කළ හැක.
function getGreeting(): string {
// return 123; // This would be an error
return "Hello!";
}
console.log(getGreeting());මේවා ද TypeScript හි වෙනම types ලෙස පවතී.
let u: undefined = undefined;
let n: null = null;
let name: string | null = "Kamal"; // Can be a string or null
name = null; // This is allowedstring | null යනු Union Type එකකි. එය අපි ඉදිරි පාඩම් වලදී ඉගෙන ගනිමු.Types යෙදූ function එකක් මගින් සෘජුකෝණාස්රයක වර්ගඵලය සොයමු.
function calculateArea(width: number, height: number): string {
const area = width * height;
return `The area is ${area} square units.`;
}
console.log(calculateArea(10, 20));The area is 200 square units.