Class 侦听抽象变量的更改
我有一个抽象类:Class 侦听抽象变量的更改,class,typescript,attributes,abstract,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所做的更改,但要保持其抽象性,以确
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
所做的更改,但要保持其抽象性,以确保程序员在某个地方设置/实现该属性
是否有办法确保程序员设置该变量,或者至少要求他声明该变量
不确定这是否可行。您可以拥有一个受保护的构造函数,该构造函数接收
名称:
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