beraliv

Mapped Types in functions

Example of Chainable Options use
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
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
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
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
Solution

That's it 💪

Don't forget to check the solution in Playground

Have a nice day ☀️

typescript
Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter