Is it possible to override a method on a Typescript class and define different parameter types using generics? I want to do this to create a flexible abstract base class, but then benefit by strict typing on the child class.
I suspect this could be another example of the "correlated union types" issue but in this case I wonder since by using interfaces, surely TypeScript does know enough information not to produce an error.
The below code produces the following error in TypeScript v4.6.3 against the doSomething override in class B:
TS2416: Property 'doSomething' in type 'B' is not assignable to the same property in base type 'A'.
Type '(opts: BOpts) => void' is not assignable to type '<T extends AOpts>(opts: T) => void'.
Types of parameters 'opts' and 'opts' are incompatible.
Type 'T' is not assignable to type 'BOpts'.
Property 'bar' is missing in type 'AOpts' but required in type 'BOpts'.
interface AOpts {
foo: number;
}
class A {
public doSomething<T extends AOpts>(opts: T) {
console.log(opts.foo);
}
}
interface BOpts extends AOpts {
bar: number;
}
class B extends A {
// this line errors
public override doSomething(opts: BOpts) {
super.doSomething(opts);
console.log(opts.bar);
}
}