Typescript: Partial<this> som parametertyp fungerar inte
Jag försöker få följande kod att kompilera, men det misslyckas i C.inc-metoden med meddelandet:
error TS2345: Argument of type '{ counter: number; }' is not assignable to parameter of type 'Partial<this>'.
Koden går inte att kompilera:
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
})
}
}
Men följande kod kan kompilera (utan C.inc-metoden):
let c = new C();
c.clone({ counter: c.counter + 1 });
Jag vill veta varför.
Svar #1
Jag vet inte varför Partial<this> inte fungerar, men Pick fungerar:
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
})
}
}
Jag skulle älska att få veta anledningen!
