How do you get the return type of an existing function using ReturnType?
ReturnType<typeof fn> gives the type a function returns. You need typeof because ReturnType expects a type, not a value, and a function name is a value.
Explain it simply
You have a function that builds a user object, and now you want a type describing that object. Writing the interface by hand means two places to update when the function changes.
ReturnType reads the answer from the function itself. The extra typeof converts the function value into its type, because utility types only accept types. If the function is generic or overloaded, ReturnType picks the last overload or the constraint, so be careful there.
Example
function createUser(name: string) {
return { id: Date.now(), name, active: true };
}
type User = ReturnType<typeof createUser>;
// { id: number; name: string; active: boolean }
const u: User = { id: 1, name: "Asha", active: false };
// Async functions return a Promise; unwrap with Awaited
async function load() { return { count: 3 }; }
type Raw = ReturnType<typeof load>; // Promise<{ count: number }>
type Data = Awaited<ReturnType<typeof load>>; // { count: number }
// ReturnType<createUser> without typeof is an errorWhat to say in the interview
"ReturnType<typeof fn> extracts what a function returns so the type stays in sync with the code. typeof is needed because the argument must be a type. For async functions I wrap it in Awaited to get the resolved value."
Common mistakes
- Writing ReturnType<createUser> and getting a 'refers to a value' error.