Upon execution, an error will be generated with the following message:
The property 'update'
within the type 'SubClass'
cannot be assigned to the same property in the base type 'MyClass'
.
The type
'(id: ID, obj: HashMap) => void'
is not compatible with the type '{ (obj: HashMap): any; (id: ID, obj: HashMap): any; }'
.
The reason behind this error lies in the requirement that when overriding a method, it must possess the exact identical type as the original method. As the method in `MyClass` is of an overloaded type with two alternatives, while the overridden method only has one.
Hence, it is imperative to explicitly specify the exact overloads even if they are not strictly needed in the subtype:
class SubClass extends MyClass {
update(obj: HashMap);
update(id: ID, obj: HashMap);
update(objOrId: HashMap | ID, obj?: HashMap) {
console.log('here I want to use both params');
}
}
Keep in mind that TypeScript will solely emit the ultimate function definition, without any runtime validation for the parameter types. Therefore, you still need to handle scenarios where only a `HashMap` may be passed to your instance of `SubClass`. This consideration is especially crucial in light of the Liskov substitution principle, which dictates that any instance of `SubClass` should be usable as an instance of `MyClass`; hence passing just a `HashMap` is perfectly acceptable.
Example on TypeScript playground