Building ReturnType and Parameters from Scratch
Recreate built-in utility types using infer.
Goal: Recreate Built-in Utilities
TypeScript ships ReturnType and Parameters as built-ins. Rebuilding them from scratch cements your understanding of infer and conditional types.
// Built-in versions (for reference)
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;Step 1: MyReturnType
We constrain T to any function, match the return position with infer R, and return R on match.
type MyReturnType<T extends (...args: any[]) => any> =
T extends (...args: any[]) => infer R ? R : never;
type A = MyReturnType<() => string>; // string
type B = MyReturnType<(x: number) => boolean>; // booleanAll lessons in this course
- Understanding infer in Conditional Types
- Building ReturnType and Parameters from Scratch
- Deeply Nested Inference Patterns
- Practical infer Use Cases: Unwrapping Promises