监听抽象变量的变化

Listen changes on abstract variable

所以我有这个摘要class:

export abstract class Foo {
    // Can't do this, but I want to make sure the implementation sets "name"
    //abstract name: string;

    set name(value: string) {
        // Do things
    }
}

正如我在代码中所述,我想监听 Foo class 中属性 name 的变化,但保持抽象以确保程序员 sets/implements某处的属性。

有没有办法确保程序员设置该变量,或者至少要求他声明它。

不确定这是否可行。

你可以有一个受保护的构造函数接收 name:

abstract class Foo {
    protected constructor(public name: string) {}
}

或者你可以声明一个抽象方法returns它:

abstract class Foo {
    public name: string;

    protected constructor() {
        this.name = this.getName();
    }

    protected abstract getName(): string;
}

您可以在不同的 place/time 而不是在构造函数中调用 getName