Generics typescript中的泛型无法正常工作?
这不应编译,但它可以:Generics typescript中的泛型无法正常工作?,generics,typescript,Generics,Typescript,这不应编译,但它可以: var thingsWithName: { name: string }[] = [{ 'name': 'A' }, { 'name': 'B' }]; function doStuff <T extends { id: number }> (thingWithId: T): T { return thingWithId; } thingsWithName.map(doStuff); var thingsWithName:{name:string
var thingsWithName: { name: string }[] = [{ 'name': 'A' }, { 'name': 'B' }];
function doStuff <T extends { id: number }> (thingWithId: T): T {
return thingWithId;
}
thingsWithName.map(doStuff);
var thingsWithName:{name:string}[]=[{'name':'A'},{'name':'B'}];
函数doStuff(thingWithId:T):T{
返回thingWithId;
}
thingsWithName.map(doStuff);
正如您可以看到的那样,thingsWithName
没有id
,因此在将doStuff
传递到映射时,typescript编译器应该对此发出警告
为什么要打字?我做错什么了吗?请参阅
小组概述的原因如下:
我们的可分配关系忽略了签名中的泛型和约束。它只是将所有类型参数替换为任何类型参数
。。。我们忽略泛型,因为我们相信考虑它们会很慢。一般来说,如果签名是泛型类型的,它会导致无止境的递归。正因为如此,这似乎不值得
在代码中,请注意,非泛型版本将引发错误:
function doStuff(thingWithId: { id: number }): { id: number } {
return thingWithId;
}
thingsWithName.map(doStuff); // error
另外请注意,由于typescript使用结构类型检查类型,因此非泛型版本将发生以下情况:
var arrayWithId = [{ id: 2, myOtherProperty: "other value" }],
arrayWithoutId = [{ noIdProperty: 2 }];
arrayWithId.map(doStuff); // ok
arrayWithoutId.map(doStuff); // error