How to extract return types of functions in TypeScript

In my last article, I talked about the 'Parameters<T>' utility type in TypeScript which is used to get the types of the parameters of a function. After extracting function parameters using Parameters<T>, the next logical question is - "What if we want to extract the return type of a function?" That’s exactly what 'ReturnType<T>' helps us do. 'ReturnType<T>' takes a function type and gives us the type of the value it returns. This is incredibly useful when you’re reusing the result of a function elsewhere or you’re wrapping or composing functions, or maybe you want to avoid manually updating types if the function’s return type changes. Just like 'Parameters<T>,' it pairs perfectly with 'typeof.' You can pass an existing function directly, and TypeScript will automatically infer the return type for you. But things get interesting when async functions enter the picture. An 'async' function will return a 'Promise,' which means 'ReturnType<typeof fn>' gives you something like 'Promise<X>' instead of just 'X'. To handle that, TypeScript has 'Awaited<T>,' a utility type that unwraps the resolved type from a Promise. So, if you combine both, you get the actual value type returned by an async function. In other words, 'Awaited<ReturnType<typeof fn>>' gives you the true resolved type. This combination becomes super useful when writing helpers or working with async workflows where you want full type safety. Together, 'ReturnType' and 'Awaited' give you a clean, readable, and type-safe way to infer what a function, synchronous or asynchronous, really returns. #TypeScript #Programming #WebDevelopment #Coding #JavaScript

  • text

To view or add a comment, sign in

Explore content categories