Append to Object in TypeScript

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

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 –

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

It’s available in here –

Remove intersection

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

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

Just apply it in AppendToObject and that’s it 😅

Check out the final solution –

Thanks for reading and have a good evening 🌆


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 ↘️