How to easily make a type from a function's parameters in TypeScript?

Published May 18, 2022

To easily make a type from the function's parameters in TypeScript, you can use the Parameters utility type and pass the function type declaration which you need to get the parameter types from as the first type argument.

TL;DR

// a simple function
function sayGreeting(name: string, greeting: string) {
  return `${greeting}, ${name}`;
}

// make type from function's parameters
// using the `Parameters` utility type
type OnlyFunctionParameters = Parameters<typeof sayGreeting>; // [name: string, greeting: string]

Let's say we have a function called sayGreeting that accepts 2 parameters called name and greeting both having the type of string like this,

// a simple function
function sayGreeting(name: string, greeting: string) {
  return `${greeting}, ${name}`;
}

Now to get the type of parameters in the sayGreeting function, we can use the Parameters utility type and then pass the type of the sayGreeting function.

Now you might ask how can we get the type of a function, for that we can use a nifty operator called typeof followed by writing the name of the function. This will automatically infer the function entire type including parameters and the return type. We can then pass this as the first type argument to the Parameters utility type.

It can be done like this,

// a simple function
function sayGreeting(name: string, greeting: string) {
  return `${greeting}, ${name}`;
}

// make type from function's parameters
// using the `Parameters` utility type
type OnlyFunctionParameters = Parameters<typeof sayGreeting>; // [name: string, greeting: string]

Now if you hover over the OnlyFunctionParameters you can see an array of types. You can use this as a type for variables that are of array type in TypeScript.

We have successfully made a type from the function parameters in TypeScript. Yay 🥳!

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter