TypeScript Annotations

In TypeScript, annotations refer to type annotations, which are used to explicitly specify the types of variables, function parameters, return values, and more. Type annotations help TypeScript catch errors at compile time, provide better code readability, and improve IDE support with features like autocompletion and type checking.

 In TypeScript, type annotations are used to explicitly specify the types of variables, function parameters, and return values. Here's how you can write basic type annotations:

  • Variable Type Annotations
  • Function Type Annotations
  • Object Type Annotations
  • Union & Intersection Types
  • Type Inference (without annotations)

Syntax:
Type annotations are written using a colon : followed by the type.

        // Variable Annotation
        let username: string = "Mohan";
        let age: number = 30;
        let isTrainer: boolean = true;

        // Array Annotation
        let skills: string[] = ["React", "Node.js", "MongoDB"];

        // Object Annotation
        let person: { name: string; age: number } = { name: "Mohan", age: 30 };

        // Function Annotation
        function greet(name: string): string {
        return `Hello, ${name}!`;
        }

Why Use Type Annotations?

Error Detection:
Catches type-related errors during development
Code Readability :: Makes it Clear what type of data is expected
IDE Support :: Enhances autocompletion,refactoring, and documentation features