监听抽象变量的变化

时间:2017-07-01 20:20:46

标签: class typescript attributes abstract

所以我有这个抽象类:

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类中对属性name所做的更改,但要保持抽象,以确保程序员在某处设置/实现属性。

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

不确定这是否可行。

1 个答案:

答案 0 :(得分:1)

您可以拥有一个受保护的构造函数,该构造函数接收name

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

或者你可以声明一个返回它的抽象方法:

abstract class Foo {
    public name: string;

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

    protected abstract getName(): string;
}

您可以在不同的地方/时间而不是在构造函数中调用getName