Open In App

What is Type Annotations in TypeScript ?

Last Updated : 14 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript Type Annotations are a way of explicitly typing the variables, functions, return values, parameters, or any other thing used in the TypeScript program. It provides the functionality to statically type the variables which makes it easier for developers to catch the type-related errors during the development instead of catching them at runtime. This mechanism of typing variables makes TypeScript a statically typed language. Type Annotations make it easier to debug applications and write a cleaner error-free code.

Example: The below code explains how you can explicitly type different parts of the TypeScript program.

Javascript
const str: string = "GeeksforGeeks";
const num: number = 6;
const arr: (number | string)[] = 
    ["GFG", "TypeScript", 500, 20];
    
console.log(typeof str);
console.log(typeof num);
console.log(arr);

Output:

string
number
["GFG", "TypeScript", 500, 20]

Type Annotations with Functions

Type Annotations with Functions in TypeScript involve explicitly specifying the types of function parameters and return values. This approach ensures that functions accept only the expected types of arguments and return values, thereby reducing the likelihood of type-related errors.

Example: The add function takes two parameters of type `number` and returns their sum, also of type number. Invoking add(5, 3) yields 8, assigned to result.

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

const result: number = add(5, 3);
console.log(result); // Output: 8

Output:

8

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads