Generic function

Even if the generic type is not specified, TS is derived from the argument.

function identity<T>(arg: T):T{return arg} function identity(" ABC "){return "ABC"} function identity<string>(" ABC "){return "ABC"}Copy the code

All kinds of writing

interface GenricIdentityFn{
    <T>(arg: T):T;
}

interface GenricIdentityFn1<T>{
    (arg:T):T
}
Copy the code

A generic class

Note: The [type parameter T] of a generic class restricts only the instance methods and attributes of the class. Has no effect on static methods or properties.

class GenericNumber<T>{
    zeroValue: T;
    add: (x:T, y:T) => T
}
Copy the code

The effect of extends in a function

Generics are unconstrained and can be any type, and using extends you can restrict the type of a generics. Force the generic T to have the length attribute

interface Lengthwis { length: number; } function loggingIdentity<T extends Lengthwise>(arg: T):T { console.log(arg.length) } function loogingIdentity<T>(arg: T):T{// error console.log(arg.length)}Copy the code

Using Type Parameters in Generic Constraints

Keyof returns a union type

function getProperty<T, K extends Keyof T>(obj:T, key: K){return obj[key]} const x = {a:1} getProperty(x, b)Copy the code

Use class types in generics

New stands for the constructor

function create<T>(c: { new (): T}):T  {
    return new c()
}



class BeeKeeper{
    hasMask: boolean = true
}
class ZooKeeper{
    nameTag: string = "Mikle"
}
class Animal{
    nameLegs: number = 4
}
class Bee extends Aniaml{
    keeper: BeeKeeper = new BeeKeeper()
}
class Lion extends Animal{
    keeper: ZooKeeper = new ZooKeeper()
}

function createInstance<A extends Animal>(c: new () => A): A{
    return new c()
}
createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;
Copy the code