Syntax
function convert(value: string): number;
function convert(value: number): string;Examples
Correlated Function Overloads: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints 13, then 12.
function convert(value: string): number;
function convert(value: number): string;
function convert(value: string | number): number | string {
return typeof value === "string" ? Number(value) : String(value);
}
console.log(convert("12") + 1);
console.log(convert(12).toUpperCase());- Expected result: The program prints 13, then 12.
- A string argument selects a number return type.
- A number argument selects a string return type even though the shared implementation uses a union.
Best practices
- Prefer a union parameter when all cases have the same return type.
- Check conversion validity where Number can produce NaN.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook