gpt4 book ai didi

typescript - 在继承的静态类方法中错了this

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

问题涉及 TypeScript 类型问题。

这段代码

class Foo {
static classFoo() {
return new this();
}
}

class Bar extends Foo {
instanceBar() {}
}


Bar.classFoo().instanceBar();

错误结果:

Property 'instanceBar' does not exist on type 'Foo'

当然,这不是真的,因为 this === BarBar.classFoo() 被调用时。由于继承在 ES6 类中的工作方式,在忽略类型错误的情况下,代码按预期工作。

为什么会这样?这是一个已知的错误吗?如何解决?

最佳答案

这是一个known issue ,当前的解决方法是

class Foo {
static classFoo<T extends Foo>(this: { new (): T } & typeof Foo): T {
return new this();
}
}

关于typescript - 在继承的静态类方法中错了this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44110257/

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