2017-07-01 75 views
0

所以我有这个抽象类:听抽象变量的变化

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

你可以有一个保护的构造函数接收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而不是在构造函数中。