TypeScript - 泛型、类型推断详解(结合官网、会持续补充)

泛型

泛型类型

泛型函数类型和非泛型函数类型并没有什么不同,只是前面加上了类型参数,类似于函数声明。
另外我们可以使用不同的泛型函数参数名,还可以使用带有签名的对象的字面量来声明函数

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

用接口来声明函数

用接口来声明函数,很像上面所说的带有签名的对象字面量声明的泛型函数

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

我们可以把泛型参数类型作为接口的参数传进来

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

泛型类

泛型类和泛型接口类似

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; };

泛型约束

可以用接口来约束泛型

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

类型推断

没有指明变量的地方,类型推断会提供帮助类型。

let x = 3

已经推断x为number类型,如果进行其他类型赋值操作,就会报错

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

最佳通用类型

let x = [1,null]

推断x的类型,我们有两种选择 number | null 。计算通用类型算法时会考虑所有的候选类型,给出一个兼容所有候选类型的类型。

猜你喜欢

转载自blog.csdn.net/qq_45859670/article/details/125621096
今日推荐