我试图编译以下代码,但在 C.inc
方法中失败并显示消息:
error TS2345: Argument of type '{ counter: number; }' is not assignable to parameter of type 'Partial<this>'.
代码无法编译:
class B {
clone(diff: Partial<this>): this {
return this; // omit the implementation.
}
}
class C extends B {
counter = 0;
inc() {
return this.clone({
counter: this.counter + 1
})
}
}
但是下面的代码可以编译(没有C.inc
方法):
let c = new C();
c.clone({ counter: c.counter + 1 });
我想知道为什么。
最佳答案
我不知道为什么Partial<this>
不起作用,但是 Pick
works :
class B {
clone<K extends keyof this>(diff: Pick<this, K>): this {
return this; // omit the implementation.
}
}
class C extends B {
counter = 0;
inc() {
return this.clone({
counter: this.counter + 1
})
}
}
我很想知道原因!
关于Typescript:Partial<this> 作为参数类型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47657038/