【发布时间】:2021-09-04 02:19:14
【问题描述】:
函数 createBob 有一个 TS 错误,因为 Person 是一个抽象类,我无法实例化它。 我希望该函数只接受扩展 Person 且不是抽象的类。
abstract class Person {
protected abstract type?: string
constructor(private name: string) {}
protected greet() {
console.log(`Hello ${this.name}`)
}
}
class Student extends Person {
type = "Student"
constructor(type: string) {
super(type)
}
}
class Teacher extends Person {
type = "teacher"
constructor(type: string) {
super(type)
}
}
function createPerson(ClassThatInheritsPerson: typeof Person): Person {
/*
* The ClassThatInheritsPerson should only accept classes that extend Person but are not Person
*/
return new ClassThatInheritsPerson()
}
const teacher1 = createPerson(Teacher) // should be allowed
const student1 = createPerson(Student) // should be allowed
const person = createPerson(Person) // shouldn't be allowed
【问题讨论】:
-
由于您尝试创建不带任何参数的
ClassThatInheritsPerson,因此不应同时允许Student和Teacher。这是故意的吗?
标签: typescript