TypeScript. Generics

Home » Tutorials » JavaScript » TypeScript. Generics
Today we’ll discuss generics – one of the most powerful TypeScript capabilities
Generics let you create flexible programming entities (functions, classes, interface etc.) to work with any data type

Code lesson

function myFunc<T, U>(firstArg: T, secondArg: U): [T,U] {
    console.log(firstArg);
    return [firstArg, secondArg];
}

myFunc<string, number>('123', 1);


interface Product {
    name: string;
    price: string;
}

function getFullInfo(student: Product): Product | null {
    // code
}

function getFullInfo<T, K extends keyof T>(entity: T, key: K): T | null {

}

function getFullInfo<T>(entity: T): T | null {
    // code
}

class GenericClass<T> {
    prop: T;
    func: (arg: T) => T;
}

let g = new GenericClass<number>();
g.prop = 3;
g.func = (param) => {
    return  param + 1;
}

console.log(g.func(g.prop));

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This