我很困惑如何使用
this
类型。
我想确保传递给我的函数
base
的参数始终是实例化类的超类型(子集)。我用Partial<this>
来做到这一点。但是当我尝试调用具有已知形状或接口的函数时,编译器向我抱怨:
class SuperClass {
base<Base extends Partial<this>>(args?: Base): boolean {
return true;
}
}
interface Bar {
bar: string
}
class Foo extends SuperClass implements Bar {
constructor(public bar: string) {
super();
this.base({ bar: "why" });
// Argument of type '{ bar: "why"; }' is not assignable to parameter of type 'Partial<this>'.ts(2345)
this.base<Bar>();
// Type 'Bar' does not satisfy the constraint 'Partial<this>'.ts(2344)
}
}
同样的代码,下面这样就可以了:
const f: Partial<Foo> = { bar: "" }
谁能解释为什么这在 Foo 类中使用时特别失败?