Back to questions
JuniorTheoryCommon
What does tsc report for this program?
function size(x: string): number;
function size(x: number[]): number;
function size(x: string | number[]): number {
return x.length;
}
function show(v: string | number[]) {
console.log(size(v));
}
show("abc");An error: no overload matches the call size(v)
- Expecting the implementation's
string | number[]signature to accept the call: callers see only the overloads, and the argument must fit one of them as a whole. - Expecting tsc to take the first overload: it takes the first one the argument fits, and a
string | number[]value fits neither of them.
- How would you change
sizeso that the callsize(v)compiles? - When are overloads a better choice than one union parameter?