我有这个 typescript 代码,使用过去在 typescript 2.3 下工作的泛型,但现在在 typescript 2.4.1 更严格的打字强制下崩溃了。
我编写了这个最小的代码片段来演示该问题:
class A {}
class B extends A {}
function helloA(clazz: typeof A) {}
helloA(B); // fine
class C<T> {
private c: T;
};
class D extends C<string> {}
function helloC(clazz: typeof C) {}
helloC(D); // breaks
以下 tsc 2.4.1 的错误:
test.ts(11,8): error TS2345: Argument of type 'typeof D' is not assignable to parameter of type 'typeof C'.
Type 'D' is not assignable to type 'C<T>'.
Types of property 'c' are incompatible.
Type 'string' is not assignable to type 'T'.
所以 helloA(B) 可以工作,而过去可以工作的 helloC(D) 现在坏了(如果我将 "noStrictGenericChecks": true 添加到我的 tsconfig 中,当然它可以编译)。
如果我删除 private c: T;
部分,它也会编译。请注意,在我的实际代码中,这个类成员实际上存在,但我扩展的类来自外部库,所以我无法删除它,此外,我希望它能够与它一起编译。
有什么方法可以让这段代码编译并保留字符串输入吗?
最佳答案
我不知道有什么方法可以使用 typeof C
而不将 {}
推断为泛型类型参数。幸运的是,您可以以不同的方式引用类构造函数:
type Constructor<T> = {
new(...args: any[]): T;
readonly prototype: T;
}
function helloC<T>(clazz: Constructor<C<T>>) { }
helloC(D);
通过检查对 helloC
的调用,您可以看到它推断 string
作为类型参数。
希望有帮助!
关于Typescript 2.4.1 和更严格的泛型打破了 typeof/继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45402477/