Mapped Types in functions

Example of Chainable Options use

Today we discuss Chainable Options

That’s one of the most popular challenges I’ve worked with: you need to connect the data type with event type, e.g. for your tracking or logging.

But the difference here is that you need to infer type from the calls.

Collect types from calls

First we can do is to return Chainable for a function option:

Change ReturnType for option function

Next, we say that we start from an empty object type and call after call we collect the data type in it. Let’s add T as Generic:

Added generic type T

Last but not least is the collection itself. Let’s add types for a key and a value as Generic:

Add key and value for every option call

If you check temporary solution in Playground, you will see that Type 'K' is not assignable to type 'string | number | symbol'

It means we need to apply Generic Constrain for K, it should be a string:

Solution

That’s it 💪

Don’t forget to check the solution in Playground

Have a nice day ☀️

typescriptmedium

Let's chat and have fun 🧑‍💻👩‍💻

No more often than once a week I write 📄 about TypeScript 💪, video playback 📺 and frontend related topics. You can unsubscribe in any time ↘️