TypeScript · Middle · Question 10 of 75

How do function overloads work in TypeScript?

function parse(x: string): number;
function parse(x: number): string;
function parse(x: string | number) { /* ... */ }

Explanation

Calling code sees only the overload signatures, and TS picks the first matching one from top to bottom. The implementation must be compatible with all of them. Overloads can often be replaced with a union parameter or a generic with a conditional type.

Further reading

Problem with a question

TypeScript · Middle · question 10

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz