Type Annotations

Eman Awad
Nov 19, 2023
2 min read
post_comment0 Comments
post_like0 Likes

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.

#1. Variable Declarations:

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'

#2. Function Parameters and Return Types:

function sum(x: number, y: number): number {
    return x + y;
}

Here,sumfunction must receive two parameters of typenumberand return anumberdata type.

#3. Arrays and Objects:

let prices: number[] = [100, 180, 300];
let student: { name: string, age: number } = { name: "Ali", age: 18 };

Here,pricesvariable must receive anarrayofnumbersandstudentvariable must receive anobjectwith two properties,namewhich must be astringandagewhich must be anumber.

#4. Union Type:

let id: number | string = 42;

Here,idcan receive a number or string data type.

#5. Type Aliases:

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 :

🔗Tutorials Teacher|Typescript Tutorial

You are not logged in.