Overloaded function extraction
Concept and syntax
Conditional signature extraction from an overloaded function uses its last declared overload signature, not call-site overload resolution. Here the catch-all signature exposes both return alternatives. The implementation signature is not itself a visible overload.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
function f(x:string):number; function f(x:number):string; function f(x:string|number):string|number; function f(x:string|number){return typeof x==="string"?x.length:String(x);}type R<T>=T extends (...a:never[])=>infer U?U:never;const a:R<typeof f>=f("tea"); const b:R<typeof f>=f(7); console.log(a,b);Expected output:
3 7Common mistake
Intentionally invalid; compile separately and do not execute.
function f(x:string):number; function f(x:number):string; function f(x:string|number):string|number; function f(x:string|number){return typeof x==="string"?x.length:String(x);}type R<T>=T extends (...a:never[])=>infer U?U:never;const a:R<typeof f>=true;Expected diagnostic: TS2322. The last visible signature returns string | number, excluding boolean.
Independent comparison
Without the catch-all declaration, extraction returns string, the final overload result. Expected: TS2322
function f(x:string):number; function f(x:number):string; function f(x:string|number){return typeof x==="string"?x.length:String(x);} type R=ReturnType<typeof f>; const x:R=3;Practice and recap
Remove the catch-all declaration and inspect R again.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Overloaded function extraction — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Overloaded function extraction is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function f(x:string):number; function f(x:number):string; function f(x:string|number):string|number; function f(x:string|number){return typeof x==="string"?x.length:String(x);}type R<T>=T extends (...a:never[])=>infer U?U:never;const a:R<typeof f>=f("tea"); const b:R<typeof f>=f(7); console.log(a,b);Which diagnostic and explanation match the rejected example under the lesson settings?
function f(x:string):number; function f(x:number):string; function f(x:string|number):string|number; function f(x:string|number){return typeof x==="string"?x.length:String(x);}type R<T>=T extends (...a:never[])=>infer U?U:never;const a:R<typeof f>=true;If the catch-all overload is removed, what does R<typeof f> select?