【问题标题】:Error with super structure in inheritance attempt (typescript classes)继承尝试中的超结构错误(打字稿类)
【发布时间】:2023-02-09 02:50:43
【问题描述】:

class Character {
    public readonly name: string;
    public readonly level: number;

    constructor(name: string, level: number) {
        this.name = name;
        this.level = level;
    }

    walk() {
        return `${this.name} walking!`
    }

    showMyLevel() {
        return `${this.name} has the level ${this.level}`
    }
}

class Wizzard extends Character {
    private readonly cajado: string;

    constructor(cajado: string) {
        super(name, level);
        this.cajado = cajado;
    }

    fireBall() {
        return `${this.name} fire ball!`
    }

}

const wizzard1 = new Wizzard('Ray', 8);

console.log(wizzard1.fireBall());

我希望我的 Wizard 类继承我的 Character 类并实现一个包含更多项目的构造函数。但是在 super() 我收到错误

const name: void
@deprecated

'name' is deprecated.ts(6385)
lib.dom.d.ts(17877, 5): The declaration was marked as deprecated here.
Argument of type 'void' is not assignable to parameter of type 'string'.ts(2345)
Cannot find name 'level'. Did you mean the instance member 'this.level'?ts(2663)

我认为这可能会发生,因为变量在只读模式下是私有的,但将其更改为公共变量会返回同样的问题。你能帮我吗?

【问题讨论】:

    标签: typescript class inheritance typescript-generics


    【解决方案1】:

    您需要向 Wizzard 类添加与 Character 类匹配的参数。

    class Wizzard extends Character {
        private readonly cajado: string;
    
        constructor(name: string, level: number, cajado: string) {
            super(name, level);
            this.cajado = cajado;
        }
    
        fireBall() {
            return `${this.name} fire ball!`
        }
    
    }
    

    另请注意,Wizard 是正确的拼写,而不是 Wizzard

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 2020-05-07
      • 2017-07-14
      • 2016-12-05
      • 1970-01-01
      • 2017-04-10
      相关资源
      最近更新 更多