Utility Type ReturnType in TypeScript
ReturnType is a utility type in TypeScript that determines what type a function returns. It helps avoid duplication and automatically adjusts if the function changes.
Syntax
ReturnType<T>
T— type (or reference to the function itself) from which we want to get the return value type.
TypeScript calculates the type that the function actually returns and passes it to ReturnType output.
Usage Example
Extracting function return type
function createUser(name: string, age: number) {
return {
name,
age,
createdAt: new Date(),
};
}
type UserFromFunction = ReturnType<typeof createUser>;
- Function
createUserreturns object{ name, age, createdAt }. ReturnType<typeof createUser>extracts exact type of this object (e.g.,{ name: string, age: number, createdAt: Date }).
Typing helper functions
If you have helper functions that process result from another function, you can directly use ReturnType:
function processUserData(user: ReturnType<typeof createUser>) {
console.log(user.name, user.createdAt);
// ...
}
processUserDatawill receive object with same type thatcreateUserreturns, ensuring consistency and avoiding type duplication.
Why ReturnType is Needed
- Simplification: No need to manually declare or duplicate return value type.
- Synchronization: If
createUserfunction logic changes,ReturnTypewill automatically adjust, eliminating desynchronization risk. - Flexibility: Convenient for factories or "wrappers" around functions where you need to know what exactly the original function returns.
Compatibility with Other Utilities
Sometimes ReturnType is combined with InstanceType, Parameters or other utilities (e.g., for building more complex types depending on function results).
Notes:
ReturnTypedoesn't work with some scenarios of "complex" overload functions when a function has multiple overload variants. In such cases TypeScript will try to infer a generalized or "merged" type.- If function uses generic types,
ReturnTypemay require more careful approach to account for specific specialization.
Summary
- ReturnType simplifies extracting function return value type, allowing avoiding duplication and increasing code consistency.