新属性无法在派生类构造函数中实例化

问题描述 投票:1回答:1

我在TS游乐场尝试这段代码并遇到了这个奇怪的事情

class Animal {
    constructor(public name: string) {
        this.name = name;
     }
}

    class Snake extends Animal {
        constructor(name: string, isPoisonous: boolean) {
            super(name);
            this.isPoisonous= isPoisonous;
        }
    }

当我在isPoisonous构造函数中介绍Snake属性时,TS对我说yazxswpoi。有趣的是,ES6中的相同内容编译得很好。

typescript
1个回答
0
投票

您需要设置访问级别(即'Property 'isPoisonous' does not exist on type 'Snake'')以便将某些内容设置为类变量,而不仅仅是构造函数的参数。因此,在值之前添加public可以解决您的问题。

也就是说,作为一种风格问题,向前声明这些属性可能更好:

public
© www.soinside.com 2019 - 2024. All rights reserved.