Parameters & ReturnType

Extract types directly from function signatures.

TypeScript4 min readConcept 40 of 54

Reverse Engineering Functions

Parameters<Type> extracts the arguments of a function type and returns them as a Tuple.

ReturnType<Type> extracts the value that the function returns.

Third-Party Libraries

Often, you'll use a third-party library that exports a function, but forgets to export the types for its arguments or its result.

Instead of guessing or manually copying the types, you can use these utilities to extract them directly from the function's signature. This guarantees your code stays in sync with the library.

Syntax

typescript function createUser(name: string, age: number): { id: string } { return { id: "123" }; } // Extract the return type type UserResponse = ReturnType<typeof createUser>; // { id: string } // Extract the arguments as a Tuple type UserArgs = Parameters<typeof createUser>; // [name: string, age: number] // Access just the first argument using indexed access type NameArg = Parameters<typeof createUser>[0]; // string

Try it

Hover over the utilities to see how they use the infer keyword to reach inside the function signature and pull out the specific types.

// 1. The Target Function
functioncreateUser(name: string, age: number):User{ ... }

// 2. The Extraction
type Extracted =Parameters<typeofcreateUser>;
Resulting Type
Tuple
[name: string, age: number]
How it works
T extends (...args: infer P) => any ? P : never

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If `function greet(name: string): boolean`, what is `Parameters<typeof greet>`?

Remember this

  • ReturnType<typeof fn> extracts what a function returns.
  • Parameters<typeof fn> extracts the arguments into a Tuple.
  • Use [0] to get the first argument from the Parameters tuple.
  • They are powered by the infer keyword in conditional types.

Done with this concept?

Mark it complete to track your progress. No login needed.