打字稿覆盖构造函数中的扩展属性

Typescript overriding extended property within constructor

本文关键字:扩展 属性 构造函数 覆盖      更新时间:2023-09-26

我在使用Typescript时遇到了问题,其中我扩展了一个类并覆盖了super的属性,但是当我实例化子类时,superclass属性仍然在构造函数中读取。请参阅以下示例:

class Person {
    public type:string = 'Generic Person';
    public constructor() {
        console.log(this.type);
    }
}
class Clown extends Person {
    public type:string = 'Scary Clown';
}
var person = new Person(), // 'Generic Person'
    clown = new Clown(); // 'Generic Person'
console.log(person.type); // 'Generic Person'
console.log(clown.type); // 'Scary Clown'

当我实例化小丑的实例时,我的预期行为将是"可怕的小丑"。有没有另一种方法可以实现这一点,而无需将值传递到构造函数本身或在实例化后手动触发某种 init 方法?

提前致谢:)

属性初始值设定项直接插入到构造函数的顶部,然后是手动输入的构造函数主体。所以

class Person {
    public type:string = 'Generic Person';
    public constructor() {
        console.log(this.type);
    }
}

成为

var Person = (function () {
    function Person() {
        this.type = 'Generic Person';
        // NOTE: You want a different value for `type`
        console.log(this.type);
    }
    return Person;
})();

如您所见,无法使用属性初始值设定项在父构造函数主体中获取不同的type

或者,不要使用 type 并依赖内置的 constructor 属性:

interface Function{name?:string;}
class Person {    
    public constructor() {
        console.log(this.constructor.name);
    }
}
class Clown extends Person {    
}
var person = new Person(), // 'Person'
    clown = new Clown(); // 'Clown'
console.log(person.constructor.name); // 'Person'
console.log(clown.constructor.name); // 'Clown'