Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.
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.
function createUser(name: string, age: number) {
return {
name,
age,
createdAt: new Date(),
};
}
type UserFromFunction = ReturnType<typeof createUser>;
createUser returns object { name, age, createdAt }.ReturnType<typeof createUser> extracts exact type of this object (e.g., { name: string, age: number, createdAt: Date }).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);
// ...
}
processUserData will receive object with same type that createUser returns, ensuring consistency and avoiding type duplication.createUser function logic changes, ReturnType will automatically adjust, eliminating desynchronization risk.Sometimes ReturnType is combined with InstanceType, Parameters or other utilities (e.g., for building more complex types depending on function results).
Notes:
ReturnType doesn'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.ReturnType may require more careful approach to account for specific specialization.