gpt4 book ai didi

typescript 中的泛型无法正常工作?

转载 作者:搜寻专家 更新时间:2023-10-30 21:54:10 24 4
gpt4 key购买 nike

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

var thingsWithName: { name: string }[] = [{ 'name': 'A' }, { 'name': 'B' }];

function doStuff <T extends { id: number }> (thingWithId: T): T {
return thingWithId;
}

thingsWithName.map(doStuff);

如您所见,thingsWithName 没有 id,因此 typescript 编译器在将 doStuff 传递给映射时应该对此发出警告。

为什么要进行类型检查?我做错了什么吗?

最佳答案

参见 this github issue .

团队概述的原因是:

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.

请注意,在您的代码中,非通用 版本会引发错误:

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

关于 typescript 中的泛型无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com