Typescript. Generics

function foo<T>(x: T): T {
    // calc
    return x;
}

console.log(foo<string>('hi, there'));
console.log(foo<number>(123));
// --- extends for generics
function foo2<T extends { name: string }>(x: T): T {
    // calc
    return x;
}

const Matt = {
    age: 11,
    name: 'Matt'
}

const Stanley = {
    name: 'Stanley'
}

console.log(foo2<{name: string}>(Matt));
console.log(foo2<{name: string}>(Stanley));

// also it could be defined as type
type myType = {name: string}

function foo3<T extends myType>(x: T): T {
    // calc
    return x;
}

console.log(foo3<myType>(Matt));
console.log(foo3<myType>(Stanley));

creation new instances of class

class User<T> {
    createNewInstanceOfT(type: { new(): T; }) {
        return new type();
    }
}

const user = new User<SomeClass>();
console.log(user.createNewInstanceOfT(SomeClass).toString());
This entry was posted in Без рубрики. Bookmark the permalink.