Open In App

What is Type Annotations in TypeScript ?

Last Updated : 21 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript Type Annotations allow developers to explicitly define the types of variables, functions, and other elements in the program.

  • They help catch mistakes early by ensuring the right data type is used.
  • They make the code easier to understand and follow.
  • Type Annotations help avoid errors and make the code more reliable.
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);
  • str is assigned the type string, so it will only accept string values.
  • num is a number type, ensuring it will only store numbers.
  • arr is an array that can hold both number and string types.

Output:

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

More Examples of Type Annotations

Function with Type Annotations

JavaScript
function greet(name: string): string {
    return `Hello, ${name}!`;
}
  • The greet function accepts a parameter name of type string and returns a string.
  • This ensures that both the input and output are of the expected types, preventing type-related errors.

Object with Type Annotations

JavaScript
const person: { name: string; age: number } = {
    name: "Alice",
    age: 30
};
  • The person object is explicitly typed to have a name of type string and an age of type number.
  • This enforces the structure of the object, ensuring it adheres to the specified types.

Array with Type Annotations

JavaScript
const numbers: number[] = [1, 2, 3, 4, 5];
  • The numbers array is annotated to contain only number elements.
  • This prevents the inclusion of elements of other types, maintaining type safety.

Class with Type Annotations

JavaScript
class Rectangle {
    width: number;
    height: number;

    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
    }

    area(): number {
        return this.width * this.height;
    }
}
  • The Rectangle class has width and height properties, both of type number.
  • The area method returns a number, representing the area of the rectangle.

Next Article

Similar Reads