Function and method overloading in TypeScript
In Typescript, the declaration of an overload
is defined by writing overload signatures.
To do this, write some number of function signatures (usually two or more), followed by the body of the function
Be aware that the implementation signature type should be generic enough to include the overload signatures.
For example, an improper implementation signature:
1function fn(x: string): string;
2// Return type isn't right
3function fn(x: number): boolean;
4// This overload signature is not compatible with its implementation signature.
5function fn(x: string | number) {
6 return "oops";
7}
Function overloading
Define a speak
function that accepts a string
or a number
in the signature.
1function speak(message: string): string;
2function speak(num: number): string;
3function speak(m: unknown) {
4 if (typeof m === 'string') {
5 return m;
6 } else if (typeof m === 'number') {
7 return `${m}`
8 }
9 throw new Error('Unable to greet');
10}
11console.log(speak(15)); // "15"
12console.log(speak("a message")); // "a message"
In the implementation signature, m
is of value unknown
and covers both overloaded signatures.
Method overloading
Using the same technique as before, the speak
method can be included in a class.
1class Speaker {
2 speak(message: string): string;
3 speak(num: number): string;
4 speak(m: unknown): unknown {
5 if (typeof m === 'string') {
6 return m;
7 } else if (typeof m === 'number') {
8 return `${m}`
9 }
10 throw new Error('Unable to greet');
11 }
12}
13console.log(new Speaker().speak(15));
14console.log(new Speaker().speak("a message"));