typescript · level 3 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Overloads give one function several honest descriptions.
Some functions behave differently depending on what you give them. double(21) should hand back a number, but double("ha") a string. A union return type would make every caller check which one they got.
Overloads fix that. Write several signatures, each a heading with no body, then one that handles them all. Callers only see the signatures, so each call gets exactly the right return type.
The implementation's own heading must cover every , but it stays hidden. If no signature matches a call, the checker reports TS2769.
function double(value: number): number;
function double(value: string): string;
function double(value: number | string): number | string {
if (typeof value === "number") {
return value * 2;
}
return value + value;
}
const n: number = double(21);
const s: string = double("ha");
console.log(n, s); Overload signatures sit directly above the implementation, with nothing in between.
guess first
Padding with zeros. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function pad(value: string, width: number): string;
function pad(value: number, width: number): string;
function pad(value: string | number, width: number): string {
let text = String(value);
while (text.length < width) {
text = "0" + text;
}
return text;
}
console.log(pad(7, 3));
console.log(pad(true, 3));
your turn
Your turn. Finish an overload.
Finish the second signature with the type it hands back, then pick a word and a first number.
fix it
The size report will not run. Fix the overloads.
- Read the error:
TS2769says no overload matches the call on line 7. thingcould be a string or an array, but each signature only accepts one of them. Callers never see the implementation's heading.- Add a third signature above the implementation:
function size(value: string | string[]): number;
nailed it
your functions tell the truth for every call. :D
- Overload signatures have no body; one implementation handles them all.
- Callers only see the signatures, never the implementation's heading.
TS2769means no signature matches the arguments you passed.
new words in your collection
- overload
- signature
- implementation
This lesson isn’t saved. A free account remembers every lesson you finish.