打字稿中的泛型不能正常工作? [英] generics in typescript not working properly?

查看:90
本文介绍了打字稿中的泛型不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不应该编译,但它确实:

  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时会警告这个。



为什么这种类型检测?我做错了什么?

解决方案

请参阅这个github问题



团队概述的原因是:


我们的可分配关系忽略签名中的泛型和约束。它只是用任何类型的参数替换所有的类型参数。



...我们忽略泛型,因为我们认为考虑它们会很慢。一般来说,如果签名是泛型类型的,它会导致永无止境的递归。因此,这似乎不值得。


在您的代码中,请注意非泛型版本会抛出一个错误:

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:

Our assignability relation ignores generics and constraints in signatures. It just replaces all type parameters with any.

... we ignore generics because we believe taking them into account will be slow. And in general it leads to never-ending recursion if the signature was in a generic type. Because of this it seems not worth it.

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

这篇关于打字稿中的泛型不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆