Onjsdev

Share


TypeScript Generics: Passing Type


By onjsdev

Nov 26th, 2023

Generics in TypeScript provide a powerful way to create reusable components with flexibility and type safety. Generics allow you to write functions and classes that work with any data type while maintaining type safety. They enable you to create more flexible and reusable code by passing types to anohter type or interface.

Syntax

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

The syntax indicates a generic type parameter, and it can be named anything you like. In the example, identity is a generic function that returns the same value it receives.

It means that whatever type the variable T is received, the 'arg' and 'return' variables also receive this type.

For example:

const result = identity<string>("Hello, TypeScript!");

Here, we explicitly specify the type (string) when calling the identity function. As the result of this, arg and return value must be string for the type safety.

Generic Classes

You can also use generics with classes to create reusable components. For example:

class Box<T> {
    value: T;

    constructor(value: T) {
        this.value = value;
    }
}

const numberBox = new Box<number>(42);
const stringBox = new Box<string>("TypeScript Generics");

Constraints

Generics can be constrained to certain types using the extends keyword. This ensures that the generic type meets specific criteria.

interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);
    return arg;
}

Here, loggingIdentity only accepts types that have a length property.

Working with Multiple Type Parameters

You can use multiple type parameters in a generic function or class to enhance flexibility.

function pair<A, B>(first: A, second: B): [A, B] {
    return [first, second];
}

The pair function takes two generic types and returns a tuple containing both values.

Conclusion

TypeScript generics empower you to write flexible and type-safe code, enhancing the reusability of your functions and classes by providing pass types to another types.