Append key-value pair to object type in TypeScript
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:
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.
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:
It's available in here – https://tsplay.dev/Nl09GN
Remove intersection
So even now we have failed tests. Let's check why it happens:
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
:
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