问题描述
这不应该编译,但它确实:
var thingsWithName:{name:string} [] = [{' name':'A'},{'name':'B'}];
函数doStuff< T extends {id:number}> (thingWithId:T):T {
return thingWithId;
}
thingsWithName.map(doStuff);
你可以看到 thingsWithName
不要有一个 id
,所以typescript编译器在将 doStuff
传递给map时会警告这个。
为什么这种类型检测?我做错了什么?
请参阅。
团队概述的原因是:
在您的代码中,请注意非泛型版本会抛出一个错误:
pre $ function $ doStuff(thingWithId:{id:number}):{id:number} {
返回thingWithId;
}
thingsWithName.map(doStuff); //错误
另外请注意,由于typescript使用结构类型来检查类型,所以会发生以下情况 版本:
其他值}],arrayWithoutId = [{noIdProperty:2}];
arrayWithId.map(doStuff); // ok
arrayWithoutId.map(doStuff); //错误
This should not compile, but it does:
var thingsWithName: { name: string }[] = [{ 'name': 'A' }, { 'name': 'B' }];
function doStuff <T extends { id: number }> (thingWithId: T): T {
return thingWithId;
}
thingsWithName.map(doStuff);
as you can see thingsWithName
don't have an id
, so typescript compiler should warn about this when passing the doStuff
to map.
Why does this typecheck? Am I doing something wrong?
See this github issue.
The reason for this as outlined by the team is:
In your code, note that a non-generic version will throw an error:
function doStuff(thingWithId: { id: number }): { id: number } {
return thingWithId;
}
thingsWithName.map(doStuff); // error
And additionally note that since typescript uses structural typing to check the type, the following will happen with the non-generic version:
var arrayWithId = [{ id: 2, myOtherProperty: "other value" }],
arrayWithoutId = [{ noIdProperty: 2 }];
arrayWithId.map(doStuff); // ok
arrayWithoutId.map(doStuff); // error
这篇关于打字稿中的泛型不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!