The ReturnType<T> utility type in TypeScript extracts the return type of a function type, enabling you to infer and reuse the type of a function's return value without manually duplicating it.
TypeScript provides the built-in ReturnType<T> utility type, which extracts the return type of a function type T. It's a powerful tool for type inference that allows you to programmatically derive a type from an existing function's return value. This avoids manual duplication and keeps your type definitions in sync with the implementation, reducing maintenance overhead and preventing type drift.
Type Safety for Promise Resolved Values: When working with async functions, ReturnType can be combined with Awaited<T> to extract the type of the resolved promise value, making error handling and data processing type-safe.
API Client Response Types: Instead of manually defining response types for every API endpoint, you can define the fetching function once and derive the response type for consumers. This ensures the frontend type stays synchronized with the API client.
React Hook Return Types: For custom React hooks that return complex objects (e.g., useQuery, useForm), you can use ReturnType to infer the hook's return type for usage in other components, without having to re-define the shape.
Event Handler Payloads: When working with event emitters or pub/sub systems, ReturnType can be used to infer the expected payload type from the event handler definition, ensuring correct event data is passed.
Form Validation Libraries: Extract the return type of a validation function to automatically generate TypeScript interfaces for valid form data, keeping validation rules and data shapes in sync.
Testing Utilities: Mock functions can use ReturnType to ensure mock implementations match the real function's return type, preventing test drift.
ReturnType only works on function types, not generic functions with unresolved type parameters. If the function is generic and the type parameters are not specified, ReturnType will return unknown for those positions.
It does not work with overloaded functions in a way that distinguishes overloads. It returns the union of all possible return types.
For constructors (classes invoked with new), use InstanceType<T> instead of ReturnType<T>.
Does not infer return types from function expressions with implicit returns? It works correctly as long as the function is typed. ReturnType<() => 'a'> resolves to "a".
When used with complex conditional types inside the function, TypeScript may not be able to fully resolve the return type and may fall back to unknown or a less precise type.