Lesson 20 of 80
One function, several distinct call signatures — for the specific case where a single union-typed parameter can't express how the return type actually depends on which shape of argument was passed.
11 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
Is the implementation signature (the third, most general one) itself an overload that a caller could match against?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
function getElement(id: string): HTMLElement | null;
function getElement(index: number): HTMLElement | undefined;
function getElement(idOrIndex: string | number): HTMLElement | null | undefined {
// one real implementation, handling both cases
return typeof idOrIndex === "string"
? document.getElementById(idOrIndex)
: document.querySelectorAll("*")[idOrIndex];
}
The first two signatures are overload declarations — they're what callers actually see and get checked against. The third, wider one is the implementation signature — it must be compatible with every overload above it, but callers never call it directly and it never shows up in autocomplete.
Calling getElement("app") resolves to the first overload's return type (HTMLElement | null); calling getElement(3) resolves to the second's (HTMLElement | undefined) — a single union-typed parameter/return ((idOrIndex: string | number): HTMLElement | null | undefined) couldn't express that the return type's nullability depends on which argument type was actually passed.
function makeDate(ts: number): Date; function makeDate(y: number, m: number, d: number): Date; — multiple call signatures declared.
any) and is invisible to callers; only the overload declarations above it are checked against call sites.Overloads come up less often than generics or unions, but recognizing when a union parameter genuinely isn't enough — because the return type's shape depends on which union branch was passed — is a precise, senior-level signal when it comes up.