如果我有一个类foo
:
class Foo {
id: number
name: string
sayHi() {
console.log('hi')
}
}
如何确保从 foo 扩展的任何类都必须设置 id
和 name
的值?
class Bar extends Foo {
// must set these values
id = 1
name = 'bar'
}
这个概念或模式有名称吗?我不能将 Foo 作为接口(interface),因为它必须具有继承类可以使用的方法。
最佳答案
给Foo
需要它们作为参数的构造函数:
class Foo {
constructor(public id: number, public name: string) {
// Validate them here if desired
}
sayHi() {
console.log('hi');
}
}
由于子类必须调用其父类(super class)构造函数(隐式或显式),因此尝试在不传入必要参数的情况下执行此操作将被 TypeScript 编译器标记为: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.
}
}
请注意此处使用的有趣的 TypeScript 功能:因为我们在构造函数参数上给出了访问修饰符,所以在调用构造函数时会自动创建实例属性并将其设置为这些值。它相当于:
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
。)
关于javascript - 如何确保扩展类必须在 TypeScript 中设置属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43376854/