Function Overloads For Precise Signatures
Declare overload signatures so callers get precise return types per argument shape, with one implementation handling the union.
Code
// 重载签名:调用方按参数形状得到精确返回类型
function parseInput(raw: string): string[];
function parseInput(raw: number): string;
function parseInput(raw: string | number): string | string[] {
if (typeof raw === 'number') return String(raw * 2);
return raw.split(',');
}
const fromNumber = parseInput(21); // string
const fromString = parseInput('a,b'); // string[]
console.log(fromNumber.toUpperCase(), fromString.length);
// 实现签名对外不可见:只能按重载调用
// parseInput(true); // 编译错误
// 常见用途:可选参数导致的联合返回收窄
function firstOrAll(items: string[]): string;
function firstOrAll(items: string[], all: true): string[];
function firstOrAll(items: string[], all?: true): string | string[] {
return all ? items : items[0] ?? '';
}
console.log(firstOrAll(['x', 'y']), firstOrAll(['x', 'y'], true));Output
Captured from a sandboxed run of this snippet in the build pipeline.
42 2
x [ 'x', 'y' ]Inside the snippet
The working surface is the functions parseInput and firstOrAll — everything else is wiring.
Points of care
- The guard
typeof raw === 'number'short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The entry-point signature is function parseInput(raw: string)
Key statements
return all ? items : items[0] ?? '';
if (typeof raw === 'number') return String(raw * 2);
return raw.split(',');
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. The file defines `parseInput`, `firstOrAll` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.