gpt4 book ai didi

typescript - TS2322 : 'T' could be instantiated with an arbitrary type which could be unrelated to 'SuperClass'

转载 作者:行者123 更新时间:2023-12-05 05:00:01 25 4
gpt4 key购买 nike

我有一个包含大量子类的基类。

class SuperClass{
constructor(){}
}
class SubClass1 extends SuperClass{
constructor(){super()}
SubClass1Prop(){}
}
class SubClass2 extends SuperClass{
constructor(){super()}
SubClass2Prop(){}
}

我有一个包含不同子类混合的列表,我已将其类型声明为 SuperClass[],因为它们共享同一个祖先。

let list:SuperClass[] = [];
list.push(new SubClass1());
list.push(new SubClass2());

我有一个函数将子类作为参数,然后过滤列表以返回该子类的实例。

此函数的类型声明取自此 SO 答案 ( Type for function that takes a class as argument, and returns an instance of that class ),略有不同的是我返回的是列表而不是单个对象。

错误就在这里。我控制什么类型可以传递给 filterList 函数,并且可以保证它永远是 SuperClass 的子类。但是,TypeScript 无法知道这一点。我如何声明我传递给此函数的任何类名必须始终是父类(super class)的子类,并且不能是“任意类型”?

function filterList<T>(className: { new():T }):T[] {
//TS2322: Type 'SuperClass[]' is not assignable to type 'T[]'.   
// Type 'SuperClass' is not assignable to type 'T'.     
// 'T' could be instantiated with an arbitrary type which could be unrelated to 'SuperClass'
return list.filter(obj => obj instanceof className);
}

上述功能的示例使用场景。 (删除了空安全检查以简化演示目的)

我要求 filteredList 被正确识别为 SubClass1[] 类型,而不是 SuperClass[]any[] 类型,没有使用“as”关键字显式类型转换。目前这些要求都满足了,但是TS错误在上面的函数中。任何解决方案都不能破坏此处的类型检查。

let filteredList = filterList(SubClass1);
filteredList[0].SubClass1Prop();

最佳答案

虽然它更容易,但您可以使用 InstanceType连同 generic parameterstype guards达到同样的效果:

function filterList<T extends { new (...args: any): any }>(className: T): InstanceType<T>[] {
const isT = (potentialT: any): potentialT is InstanceType<T> => {
return potentialT instanceof className;
}
return list.filter<InstanceType<T>>(isT);
}

Playground

关于typescript - TS2322 : 'T' could be instantiated with an arbitrary type which could be unrelated to 'SuperClass' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63322109/

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