beraliv

Append key-value pair to object type in TypeScript

Example of AppendToObject use
Example of AppendToObject use

Today we discuss AppendToObject

In JavaScript we don't have a method for that, but spread with adding extra field is similar to what we want to do.

Let's try to solve it 🚀

Add key and value

First of all, we need to add the value by the key. Let's try out https://tsplay.dev/w62Yew:

Add value by key, version 1
Add value by key, version 1

But unfortunately we cannot use type U as a value here.

Instead we say that we iterate over elements from U – https://tsplay.dev/WP5XJw.

Add value by key, version 2
Add value by key, version 2

But this is also not working as U should have the specific type to be a key in an object – PropertyKey. In this case we need to add Generic Constrain:

Add value by key, final version
Add value by key, final version

It's available in here – https://tsplay.dev/Nl09GN

Remove intersection

So even now we have failed tests. Let's check why it happens:

Example with intersection
Example with intersection

We have an intersection because we use &, but we need to get rid of it to have one result object.

To fix that, we can create auxiliary type RemoveIntersection:

Remove intersection
Remove intersection

Just apply it in AppendToObject and that's it 😅

Check out the final solution – https://tsplay.dev/wRpLQm

Thanks for reading and have a good evening 🌆

typescript
Alexey Berezin profile image

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