Search code examples
typescriptinheritanceclass-method

Override method with different argument types in extended class - Typescript


I want to override a method and pass different argument types to it:

class Base {
    public myMethod(myString: string): undefined {
        return;
    }
}

class Child extends Base {
    public myMethod(myNumber: number): undefined {
        return super.myMethod(String(myNumber));
    }
}

Yet this yields a typescript error:

Property 'myMethod' in type 'Child' is not assignable to the same property in base type 'Base'. Type '(myNumber: number) => undefined' is not assignable to type '(myString: string) => undefined'. Types of parameters 'myNumber' and 'myString' are incompatible. Type 'string' is not assignable to type 'number'.

Is there a way to do this without creating a typescript error?


Solution

  • There is not a way to do this*. In TypeScript, inheritance implies subtyping, so you can't inherit from a base class while not being a valid subtype of it.

    * Technically not true but I'm not going to mention them because they're gross hacks that you shouldn't do.