【问题标题】:Property 'x' does not exist on type 'never'“从不”类型上不存在属性“x”
【发布时间】:2017-04-09 08:18:35
【问题描述】:

在下面的代码中,Typescript 编译器说属性 'doit' 在类型 'never' 上不存在。这可能是编译器错误吗?

class X {
    public foo(): void {
        if (this instanceof Y) {
        } else {
            this.doit();
        }
    }

    private doit(): void {
    }
}

class Y extends X {
}

我找到了以下解决方法:

const temp = (this instanceof Y);
if (temp) {
} else {
    this.doit();
}

编译器对这个等效代码没有任何问题,这再次让我怀疑这里存在编译器错误。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    是的,这似乎是一个错误:InstanceOf incorrectly narrow when two type extends same base class

    但是,无论如何,你这样做的意义何在?
    如果您希望 fooY 的实例中表现不同,那么为什么不在 Y 中覆盖它:

    class Y extends X {
        public foo(): void {
            ...
        }
    }
    

    如果doit 仅在Y 实例中需要,则它应该在Y 中,如果两者都需要,则可以在X 中进行保护。

    【讨论】:

    • 这是出于遗留原因需要的 hack,即 Y 的源代码无法更改。
    猜你喜欢
    • 2019-01-11
    • 2020-12-18
    • 1970-01-01
    • 2021-12-11
    • 2017-10-24
    • 1970-01-01
    • 2021-12-30
    • 2018-03-09
    • 2018-04-03
    相关资源
    最近更新 更多