Overload signatures
Concept and syntax
Overloads give callers multiple signatures with distinct parameter and return relationships. Place overload declarations before a compatible implementation. When calls differ only by input type but return the same type, a union parameter is often simpler. A call must match an exposed signature.
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 convert(x:string):number;function convert(x:number):string;function convert(x:string|number):string|number {return typeof x==="string"?x.length:String(x);}const n:number=convert("tea");const s:string=convert(4);console.log(n,s);Expected output:
3 4For a text input the selected signature promises a number and the body returns length. For a numeric input the second signature promises a string and the body calls String. The annotations on n and s check that correlation.
Common mistake
Intentionally invalid; compile separately and do not execute.
function convert(x:string):number;function convert(x:number):string;function convert(x:string|number):string|number {return typeof x==="string"?x.length:String(x);}convert(true);Expected diagnostic: TS2769. Neither overload accepts boolean. Choose a supported input or add a valid overload and implementation branch.
Practice and recap
Add a boolean overload with a distinct result contract.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Overload signatures — 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 convert(x:string):number;function convert(x:number):string;function convert(x:string|number):string|number {return typeof x==="string"?x.length:String(x);}const n:number=convert("tea");const s:string=convert(4);console.log(n,s);Which diagnostic and explanation match the rejected example under the lesson settings?
function convert(x:string):number;function convert(x:number):string;function convert(x:string|number):string|number {return typeof x==="string"?x.length:String(x);}convert(true);