While reading the method overriding part of the Typescript documentation, I came across something interesting. Normally the method of base class would not be referenced while overriding method in javascript. But it is different in typescript.
Example
class Base {
greet() {
console.log("Hello, world!");
}
}
class Derived extends Base {
/*
Property 'greet' in type 'Derived' is not assignable to the same property in base type 'Base'.
Type '(name: string) => void' is not assignable to type '() => void'.
*/
greet(name: string) {
console.log(`Hello, ${name.toUpperCase()}`);
}
}
Actually, it can be done this way.
class Derived extends Base {
greet(name?: string) {
if (name === undefined) {
super.greet();
} else {
console.log(`Hello, ${name.toUpperCase()}`);
}
}
}
But why? Is this a pattern? Do I have to do it this way when overriding method?
"Assignable" in typescript simply means that the parameter and return types overlap.
You have these signatures:
greet(): void;
greet(name: string): void;
Since the parameter types don't overlap, typescript warns you that the signature is not assignable to the base method.
If you change the second method to greet(name?: string): void;
then the parameter types overlap (? means a parameter is optional)) and typescript doesn't need to warn you, because you need to manually check if name is available or not.