Reputation: 12005
I have abstract method:
abstract setProp<T, K extends keyof T>(value: keyof T, key: K);
I tried to override this in class heir:
public setProp<IParentProfile, K extends keyof IParentProfile>(value: keyof IParentProfile, key: K) {
this.model[key] = value;
}
But interpretation says me an error:
Incompatible override method from abstract class, where did I make mistake?
Also I tried this way:
abstract setProp<T, K extends keyof T>(model: T, value: keyof T, key: K): T;
And using:
public setProp<IParentProfile, K extends keyof IParentProfile>(model: IParentProfile, value: keyof IParentProfile, key: K) {
return model[key] = value;
}
Can you see why this does not work please
Upvotes: 3
Views: 1834
Reputation: 327819
As I said in the comments, it looks like a compiler bug. (This is only addressing the inability to override your generic method, not the code you added in the link later.)
The following is currently an error in TypeScript 2.9 and below:
class A {
m<T, U extends T>(t: T, u: U) { }
}
class B extends A {
m<T, U extends T>(t: T, u: U) { }
//^--error, T is not assignable to T
}
It seems that you can't override a generic method if its generic constraints use type parameters.
I filed Microsoft/TypeScript#25373 and it has (as of 2018-07-02) been classified as a bug, which is slated to be addressed in TypeScript 3.1.
Until then, I guess you need to use workarounds. Actually, the only workaround I can find that lets you override abstract
generic methods using type-parameter constraints is the sledgehammer of workarounds, the @tsignore
comment:
class A {
m<T, U extends T>(t: T, u: U) { }
}
class B extends A {
// @ts-ignore
m<T, U extends T>(t: T, u: U) { } // no error
}
I don't normally recommend using @ts-ignore
, because all it does is suppress the error output; it doesn't magically fix anything. But assuming the compiler bug gets fixed in the near future, it's a reasonable temporary fix.
Hope that helps; good luck!
Upvotes: 4