Sobes.tech
Junior — Middle

Have you used generics in TypeScript development?

sobes.tech AI

Answer from AI

Yes, in TypeScript, generics are widely used to create universal and reusable components, functions, and classes that work with different data types while maintaining type safety.

Example of using generics in a function:

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

const num = identity<number>(42); // num is of type number
const str = identity<string>("hello"); // str is of type string

Example with a generic class:

class Box<T> {
    private content: T;

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

    getContent(): T {
        return this.content;
    }
}

const box = new Box<number>(123);
console.log(box.getContent()); // 123

Generics allow writing more flexible and type-safe code, which is especially useful in large projects on Node.js.