TypeScript - Generics, detailed explanation of type inference (combined with the official website, will continue to be added)

generic

generic type

Generic function types are no different from non-generic function types except that they are preceded by type parameters, similar to function declarations.
In addition, we can use different generic function parameter names, and we can also use the literal value of the object with the signature to declare the function

function identity<T>(arg:T):T{
    
    
   return arg
}
let myIdentuty:<T>(arg:T)=>T = identity
let myIdentuty1:<U>(arg:U)=>U = identity    // 使用不同的泛型参数名

let myIdentuty2:{
    
                          // 我们还可以使用带有签名的对象自变量来定义泛型函数
    <T>(arg:T):T
} = identity

Declare functions with interfaces

Use interfaces to declare functions, much like the generic functions declared above with signed object literals

interface GenericIdentityFn{
    
    
    <T>(arg:T):T;
}
let myIdentuty3:GenericIdentityFn = identity

We can pass the generic parameter type as an interface parameter

interface GenericIdentityFn<T>{
    
    
    <T>(arg:T):T;
}
let myIdentuty3:GenericIdentityFn<number>= identity

generic class

Generic classes are similar to generic interfaces

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

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) {
    
     return x + y; };

Generic constraints

Interfaces can be used to constrain generics

interface Lengthwise{
    
    
    length:number
}
//对任意类型T,添加了至少要有length属性的约束
function identity<T extends Lengthwise>(arg:T):T{
    
    
   return arg
}

type inference

Where no variable is specified, type inference provides a helpful type.

let x = 3

It has been inferred that x is a number type, if other types of assignment operations are performed, an error will be reported

x = ' 123'       //不能将类型“string”分配给类型“number”。

best general type

let x = [1,null]

To infer the type of x, we have two options number | null. All candidate types are considered when computing the general type algorithm, giving a type that is compatible with all candidate types.

Guess you like

Origin blog.csdn.net/qq_45859670/article/details/125621096