avatarDr. Derek Austin 🥳

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5606

Abstract

ndlerParams</span> = <span class="hljs-title class_">Parameters</span><<span class="hljs-keyword">typeof</span> mapacheHandler></pre></div><p id="fdda">In the above snippet, <code>MapacheHandlerParams</code> is now a tuple of length 1, defined as the type of the <code>mapacheHandler</code> function’s parameters.</p><p id="f788">In case the signature of <code>CallbackFunction</code> changes, our handler function will still be in sync. Talk about keeping our mapaches well-handled! 🦝</p><h1 id="e10b">Nesting Parameters With Other Utility Types</h1><p id="fbd5">The <code>Parameters</code> type isn’t just a standalone utility; it plays well with the other <a href="https://readmedium.com/7-essential-typescript-features-every-developer-should-know-5fa3cbe625ab">built-in utility types</a> I’ve been covering here in <a href="https://medium.com/totally-typescript"><i>Totally TypeScript</i></a><i>.</i></p><div id="07f4" class="link-block"> <a href="https://medium.com/totally-typescript"> <div> <div> <h2>Totally TypeScript</h2> <div><h3>Can’t get enough TypeScript? Not sure what those <> angle brackets are for? We’ve got you covered.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*cNmov4GQyH-YqZcesL-ygg.png)"></div> </div> </div> </a> </div><p id="bf73">Let’s say we have some different use cases for the same function, such that mapaches involved in a research experiment are given numbers instead of names. That means we type the <code>name</code> prop as the union <code>string | number</code>.</p><p id="cb2f">When placing mapaches into our mapache fostering and adoption program, we need to ensure the first parameter of our mapache function is always a string, and never a number. We can use <code>Parameters</code> along with TypeScript’s built-in <code>Exclude</code> utility type to achieve this exact effect:</p><div id="f472"><pre><span class="hljs-comment">/** This is the function for the adoption & the research project. */</span> <span class="hljs-keyword">type</span> <span class="hljs-title class_">MapacheFunction</span> = <span class="hljs-function">(<span class="hljs-params">name: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span>, isCute: <span class="hljs-built_in">boolean</span></span>) =></span> <span class="hljs-built_in">void</span>

<span class="hljs-comment">/** The type here is string. */</span> <span class="hljs-keyword">type</span> <span class="hljs-title class_">ValidMapacheNames</span> = <span class="hljs-title class_">Exclude</span><<span class="hljs-title class_">Parameters</span><<span class="hljs-title class_">MapacheFunction</span>>[<span class="hljs-number">0</span>], <span class="hljs-built_in">number</span>>

<span class="hljs-comment">/**

Options

VHaYBe1us0dArObzMzmKGK7Hv8wEomWjTu5fwleroj2yj0ocFQnPg8YnkmfIlGBaCGJAGAdqAABk0EaPylCzLgAbiBiNiFjq8IfHoEFmo40A2l4dqgAAPqAUKuuQRR6hwAieFErj1ME8SsEkqTpPss5gfCK7lMUqakuY55FvCABqgLpERjB4E+oDfAAHuAtQcIKSwviQb7LER7bqgkSAAAxMJCLqxAB9I9oJDQcbYGAUDgkCrsUHT8KhS5lBUq44N5q5rsEiBQbB8G2OY4bXvgsDuPZZEUXJtQKbFhDzLAjGwMxrGgHpCzvis6XGbsSAAIxMNxvGeoliUFCBxR4H8AJAsmPkuPW7mio0ADcabkSQqZ+gA5IgMSVHR1miAlvS+RoACCcEIURDiCINTqUb42W5Zt7GQJxnbunxGQXvCS2Rat5obZ4KVpVaGUkFlom7Z4BUGcVD2ldApmVdVHrpEAA">TypeScript Playground</a> so that you can, well, play around with them! Let me know if that helps you.</p><h1 id="50c3">Wrapping Up: TypeScript’s Type for Function Params</h1><p id="361b">The <code>Parameters</code> type in TypeScript is a great utility for those who of us want a dynamic way to derive parameter types. I’m all about keeping my types thoroughly documented in one place, and then reusing them again!</p><p id="009c">This particular built-in type can be a real lifesaver, whether you prefer regular function params or passing objects as function params.</p><div id="c653" class="link-block"> <a href="https://readmedium.com/why-you-should-always-pass-objects-as-function-parameters-in-javascript-7fb7c5833dc6"> <div> <div> <h2>Why You Should Always Pass Objects as Function Parameters in JavaScript</h2> <div><h3>This code pattern, which is commonly used in React, is a much better idea than using traditional function parameters in…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Ui1k38gEy2sbUXrB)"></div> </div> </div> </a> </div><p id="c716">The <code>Parameters</code> type is as clever and nimble as our mapache friends, who already knew what tuple was before I told them. Code mapaches!!! 😡</p><p id="13cd">Next time you’re coding in TypeScript, remember mapaches and the tricks they teach us. Embrace the <code>Parameters</code> type, and elevate your type game.</p><p id="9550">And, if you liked this article, be sure to let me know by highlighting it! Doing so helps the next reader know what you found most insightful.</p><p id="7783"><b>Happy coding! </b>🐶</p><h1 id="1b6f">Further Reading: More Articles in Totally TypeScript</h1><div id="9f7a" class="link-block"> <a href="https://readmedium.com/7-essential-typescript-features-every-developer-should-know-5fa3cbe625ab"> <div> <div> <h2>7 Essential TypeScript Features Every Developer Should Know 🪶</h2> <div><h3>Elevate your TypeScript game with these powerful and often overlooked features</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*7bmWAR8Pcku3bjq6)"></div> </div> </div> </a> </div><div id="0718" class="link-block"> <a href="https://readmedium.com/why-typescript-enums-are-terrible-but-union-types-are-great-83324f571eba"> <div> <div> <h2>Why TypeScript Enums Are Terrible But Union Types Are Great</h2> <div><h3>A deep dive into the pitfalls of TypeScript Enums and the power of Union Types, or why I refactor all my Enums to Union…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*ThgmsqQnU2hWX7F_)"></div> </div> </div> </a> </div><div id="53d0" class="link-block"> <a href="https://readmedium.com/5-common-typescript-misconceptions-debunked-5ca2d81c167b"> <div> <div> <h2>5 Common TypeScript Misconceptions Debunked</h2> <div><h3>Dispelling the myths and setting the record straight for developers who want to use TypeScript for modern web dev</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*9NCSov9io54a_o1i7EajQA.jpeg)"></div> </div> </div> </a> </div><div id="553b" class="link-block"> <a href="https://readmedium.com/demystifying-typescript-decorators-real-world-use-cases-best-practices-b4ebec8d5c09"> <div> <div> <h2>Demystifying TypeScript Decorators: Real-World Use Cases & Best Practices</h2> <div><h3>What you need to know about using TypeScript decorators to streamline your code and optimize performance</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*3KG8AkSzrxCS5FOF)"></div> </div> </div> </a> </div><figure id="942f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*05EE-TxYxRoPV9Gh"><figcaption>I would love to see the function parameter type for this dog’s eyes! Photo by <a href="https://unsplash.com/@chrishcush?utm_source=medium&amp;utm_medium=referral">Christian Bowen</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure></article></body>

How To Use the Built-In Parameters Type in TypeScript

Here’s how you get the type of a function’s parameters in TypeScript.

Wahoo! Function parameters! Wahooooooooooooooooo! Photo by Jack Dong on Unsplash

Hello fellow TypeScript enthusiasts! Ever felt like diving deep into function parameter typing in TypeScript? In that case, you are in the right place! Today, I want to introduce you to a gem: the built-in Parameters type. 🦝

What Is the Parameter Type in TypeScript

If you’ve ever been in a situation where you wanted to grab the parameter types from a function, you know it’s not always straightforward.

That’s where our mapache friend, the Parameters type, comes in. It allows you to obtain a “tuple type” from the types of a function's parameters.

A tuple type is an array type with a known length, where each index position has a specified type. Think of the return type of React’s useState:

const [mapacheName, setMapacheName] = useState("rocky")

The returned value [mapacheName, setMapacheName] is a tuple of length 2. The type of this tuple is [string, Dispatch].

A Simple Example of Using Parameters<Type>

Let’s start with a basic example. To use Parameters, you pass in the function as the generic Type. It looks a little something like this:

type MapacheFeedingFunction = (food: string, quantity: number) => void

/** This type is a tuple type of length 2 */ 
type MapacheDiet = Parameters<MapacheFeedingFunction>

In the above code, MapacheDiet would be equivalent to:

/** This is the same tuple type of length 2 */ 
type MapacheDietEquivalent = [string, number]

The MapacheDiet type now holds a tuple of the parameters for our MapacheFeedingFunction. This can save you quite a bit of retyping!

You also will get the labels from the function parameters as part of the type. It’s similar to a defining an object type as {key: string]: string}:

/** When you define an object type in TypeScript, you can name the keys.
type SomeObjectType = {[keyName: string]: string}

// The actual tooltip for `MapacheDiet` includes the parameter names.
// type MapacheDiet = [food: string, quantity: number]

But more importantly, you probably never want to retype out parameter types manually; you already had to type them up the first time, right?

In all seriousness, typing them out again can easily lead to bugs and type errors, since you double your maintenance if you don’t use Parameters.

Using the Params Type with Higher-Order Functions

Where the Parameters type shines is in higher-order functions, which are functions that take another function (called a “callback”) as a parameter.

Imagine you have a function that wraps another function, but you want to be sure the wrapping function accepts the same parameters.

How do you do that? Let’s look at another example:

/** We type the callback before defining our higher-order function. */
type CallbackFunction = (mapacheName: string, age: number) => void

/** We can pass in any matching callback function to `mapacheHandler`. */
function mapacheHandler(callback: CallbackFunction) {
  callback("Ricky", 3)
}

/** The tuple type here will be `[callback: CallbackFunction]`. */
type MapacheHandlerParams = Parameters<typeof mapacheHandler>

In the above snippet, MapacheHandlerParams is now a tuple of length 1, defined as the type of the mapacheHandler function’s parameters.

In case the signature of CallbackFunction changes, our handler function will still be in sync. Talk about keeping our mapaches well-handled! 🦝

Nesting Parameters With Other Utility Types

The Parameters type isn’t just a standalone utility; it plays well with the other built-in utility types I’ve been covering here in Totally TypeScript.

Let’s say we have some different use cases for the same function, such that mapaches involved in a research experiment are given numbers instead of names. That means we type the name prop as the union string | number.

When placing mapaches into our mapache fostering and adoption program, we need to ensure the first parameter of our mapache function is always a string, and never a number. We can use Parameters along with TypeScript’s built-in Exclude utility type to achieve this exact effect:

/** This is the function for the adoption & the research project. */
type MapacheFunction = (name: string | number, isCute: boolean) => void

/** The type here is `string`. */
type ValidMapacheNames = Exclude<Parameters<MapacheFunction>[0], number>

/**
 * The tooltip shows that the type is what we want for adopting mapaches:
 * (name: ValidMapacheNames, isCute: Parameters<MapacheFunction>[1]) => void
 * 
 * This is equivalent to the following type; `name` can't be a number:
 * type AdoptMapache = (name: string, isCute: boolean) => void
 */
type AdoptMapache = (name: ValidMapacheNames, isCute: Parameters<MapacheFunction>[1]) => voidWith that, ValidMapacheNames is a type that ensures it can only be a string. No numeric raccoon names allowed for our mapache adoption program!

This example is pretty contrived, but the important takeaway is that you’ll often combine utility types like Parameters and Exclude in the same code.

I’ve put all of the code examples together into TypeScript Playground so that you can, well, play around with them! Let me know if that helps you.

Wrapping Up: TypeScript’s Type for Function Params

The Parameters type in TypeScript is a great utility for those who of us want a dynamic way to derive parameter types. I’m all about keeping my types thoroughly documented in one place, and then reusing them again!

This particular built-in type can be a real lifesaver, whether you prefer regular function params or passing objects as function params.

The Parameters type is as clever and nimble as our mapache friends, who already knew what tuple was before I told them. Code mapaches!!! 😡

Next time you’re coding in TypeScript, remember mapaches and the tricks they teach us. Embrace the Parameters type, and elevate your type game.

And, if you liked this article, be sure to let me know by highlighting it! Doing so helps the next reader know what you found most insightful.

Happy coding! 🐶

Further Reading: More Articles in Totally TypeScript

I would love to see the function parameter type for this dog’s eyes! Photo by Christian Bowen on Unsplash
Typescript
JavaScript
Programming
Web Development
Software Development
Recommended from ReadMedium