如何确保扩展类必须在TypeScript中设置属性值?
问题描述:
如果我有一个类foo
:如何确保扩展类必须在TypeScript中设置属性值?
class Foo {
id: number
name: string
sayHi() {
console.log('hi')
}
}
我怎样才能确保从富必须id
和name
设定值扩展任何类?
class Bar extends Foo {
// must set these values
id = 1
name = 'bar'
}
是否有这个概念或模式的名称?我不能将Foo
作为接口,因为它必须具有继承类可以使用的方法。
答
给Foo
要求他们作为参数的构造函数:
class Foo {
constructor(public id: number, public name: string) {
// Validate them here if desired
}
sayHi() {
console.log('hi');
}
}
由于子类必须调用它的父类的构造函数(或明或暗地),企图没有必要的参数传递将得到标记这样做打字稿编译:Supplied parameters do not match any signature of call target.
例如,这些都失败:
class Bar extends Foo {
}
const b = new Bar(); // Supplied parameters do not match any signature of call target.
和
class Bar extends Foo {
constructor() {
super(); // Supplied parameters do not match any signature of call target.
}
}
注有趣的打字稿功能使用的有:因为我们给的构造函数的参数的访问修饰符,实例属性会自动创建并设置这些值时,调用构造函数。这相当于:
class Foo {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
// Validate them here if desired
}
sayHi() {
console.log('hi');
}
}
(因为默认修饰符是public
)