In the previous articles, we learned thatTypeScriptis a statically typed language. Now, we will delve into that practically by covering the concept ofType AnnotationsinTypeScript.
Type Annotationsare a fundamental aspect ofTypeScript. They allow you to specify the type of variables, function parameters , object properties … etc.
This enforces type checking which will help us to catch errors early during development time and improve our code quality and maintenance.
Now, let's dive into It with simple examples.
let name: string = "Ali";
let age: number = 18;
let isSucceed: boolean = true;
Here we usedtype annotationsto specify the type of data that can be stored in these variables.agemust be a number,namemust be a string andisSucceedmust be a boolean.
💡Note: if you try to reassign a different data type to one of the previous variable you will get an error.
For example :
age = "20";
Here,TScompiler will through an error telling you thatType 'string' is not assignable to type 'number'
function sum(x: number, y: number): number {
return x + y;
}
Here,sum
function must receive two parameters of typenumber
and return anumberdata type.
let prices: number[] = [100, 180, 300];
let student: { name: string, age: number } = { name: "Ali", age: 18 };
Here,prices
variable must receive anarray
ofnumbers
andstudent
variable must receive anobject
with two properties,name
which must be astring
andage
which must be anumber
.
let id: number | string = 42;
Here,id
can receive a number or string data type.
Type Aliasesallow you to give meaningful names to complex types. This makes your code more readable.
type strNum = string | number
// Usage
let x: strNum = 100;
Here,strNumis atype aliasfor data type that can bestringornumber. It makes the code more readable and provides a convenient way to reuse this type.
📍References :