从概念上讲,您确实希望使用the polymorphic this
type来表示潜在子类的类型.这实质上是实现类的隐式generic类型参数constrained,只有在以后作为方法调用时才会指定:
class SuperElement {
render(subclassInstance: this) { }
}
new SuperElement().render;
// (method) SuperElement.render(subclassInstance: SuperElement): void
// this type inferred to be --------------------> ^^^^^^^^^^^^
class SomeSubElement extends SuperElement {
foo = 123;
}
new SomeSubElement().render;
// (method) SuperElement.render(subclassInstance: SomeSubElement): void
// this type inferred to be --------------------> ^^^^^^^^^^^^^^
不幸的是,当您在TypeScrip中重写方法时,子类不能从超类类型推断其参数类型.您必须自己设置annotate个参数,然后针对超类方法参数类型设置checked个参数类型,以确保兼容性.这是TypeScrip中一个长期存在的痛点;要求从父类继承参数类型的相关开放问题是microsoft/TypeScript#23911.在此之前,除非它被实施,否则,您将被困在这样做:
class MyElement extends SuperElement {
render({ sayHello }: this) {
// annotate ---> ^^^^^^
sayHello('Foo');
}
sayHello(name: string) {}
}
这不是很好,但至少捕捉到了错误:
class OopsElement extends SuperElement {
render({ sayHowdy }: this) { // error!
// ~~~~~~~~ <--
// Property 'sayHowdy' does not exist on type 'OopsElement'
}
sayHello(name: string) {}
}
Playground link to code个