Overload implementation
Concept and syntax
The implementation signature must accommodate overloads, but callers see only declared overload signatures. A broad optional implementation parameter does not automatically create an optional public call. Check each public alternative and its runtime branch separately.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function label(x:string):string;function label(x:number):string;function label(x?:string|number){return x===undefined?"empty":String(x);}console.log(label("tea"),label(7));Expected output:
tea 7Common mistake
Intentionally invalid; compile separately and do not execute.
function label(x:string):string;function label(x:number):string;function label(x?:string|number){return x===undefined?"empty":String(x);}label();Expected diagnostic: TS2554. The implementation accepts omission internally, but neither public overload permits it. Add a zero-argument overload if intended.
Practice and recap
Add a zero-argument overload and verify the empty branch.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Overload implementation — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function label(x:string):string;function label(x:number):string;function label(x?:string|number){return x===undefined?"empty":String(x);}console.log(label("tea"),label(7));Which diagnostic and explanation match the rejected example under the lesson settings?
function label(x:string):string;function label(x:number):string;function label(x?:string|number){return x===undefined?"empty":String(x);}label();