Type Annotations in TypeScript

Learn how to use Type Annotations in TypeScript with this detailed tutorial. Includes basic and advanced examples to help you master Type Annotations.

Introduction

Type Annotations in TypeScript allow you to explicitly define the types of variables, function parameters, and return values. This helps catch errors at compile-time, improves code readability, and provides better tooling support.

Basic Examples

Here are some basic examples of using Type Annotations in TypeScript:

Variables

You can specify the type of a variable using a colon (:) followed by the type name.

let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];

Functions

Type Annotations can be used for function parameters and return types.

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

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

Objects

You can define the types of properties in an object.

let person: { name: string; age: number } = {
    name: "John",
    age: 30
};

Advanced Examples

Here are some advanced examples of using Type Annotations in TypeScript:

Interfaces

Interfaces allow you to define the structure of an object.

interface Person {
    firstName: string;
    lastName: string;
    age?: number; // optional property
}

function printPerson(person: Person): void {
    console.log(`${person.firstName} ${person.lastName}`);
}

let user: Person = { firstName: "Jane", lastName: "Doe" };
printPerson(user);

Classes

You can use Type Annotations with classes to define the types of properties and methods.

class Animal {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    move(distanceInMeters: number): void {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

let dog = new Animal("Dog", 5);
dog.move(10);

Generics

Generics allow you to create reusable components that work with a variety of types.

function identity(arg: T): T {
    return arg;
}

let output1 = identity("myString"); // output1 is of type string
let output2 = identity(42); // output2 is of type number

Type Aliases

Type Aliases allow you to create a new name for an existing type.

type Point = {
    x: number;
    y: number;
};

let point: Point = { x: 10, y: 20 };

Union Types

Union Types allow a variable to hold more than one type.

function printId(id: number | string): void {
    console.log(`ID: ${id}`);
}

printId(101);
printId("202");

Intersection Types

Intersection Types combine multiple types into one.

interface ErrorHandling {
    success: boolean;
    error?: { message: string };
}

interface ArtworksData {
    artworks: { title: string }[];
}

type ArtworksResponse = ErrorHandling & ArtworksData;

let response: ArtworksResponse = {
    success: true,
    artworks: [{ title: "Mona Lisa" }]
};

Enums

Enums allow you to define a set of named constants.

enum Direction {
    Up = 1,
    Down,
    Left,
    Right
}

function move(direction: Direction): void {
    console.log(`Moving in direction: ${direction}`);
}

move(Direction.Up);

Tuples

Tuples allow you to define an array with fixed types for each element.

let tuple: [string, number];
tuple = ["hello", 10]; // OK
tuple = [10, "hello"]; // Error: Type 'number' is not assignable to type 'string'

Type Assertions

Type Assertions allow you to override the inferred type of an expression.

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

Never Type

The never type represents the type of values that never occur. It is used to indicate that a function never returns or always throws an exception.

function error(message: string): never {
    throw new Error(message);
}

function infiniteLoop(): never {
    while (true) {}
}

Conclusion

Type Annotations in TypeScript provide a powerful way to define and enforce types in your code. By using Type Annotations, you can catch errors early, improve code readability, and benefit from better tooling support. Whether you are working on a small project or a large-scale application, Type Annotations can help you write more reliable and maintainable code.