Spread in TypeScript

Example of Merge use

Today we discuss Merge

It’s quite convenient to use it in combination with ES6 spread operator for objects.

Let’s try it out 🚀

Iterate over object keys

As I previously said, EcmaScript 6 introduced the spread operator which does the same in JavaScript which we want to achieve here. Let’s have an example:

Spread in JavaScript

If we have the same key in both objects, we use if from the second object. Otherwise, we get it from the first object.

So let’s iterate over all keys of two objects in TypeScript and check whether we have a key in second object. If so, we extract value from the second object. Otherwise, we get value from the first object – https://tsplay.dev/Nl0BlN

Merge, version 1

Unfortunately, we have an error when we use F[K] as TypeScript doesn’t know in advance if K is a key of first object F. Let’s add the condition explicitly:

Merge, final version

This workaround works and that’s actually the solution – https://tsplay.dev/wRpM7m

Thank you for your time and have a wonderful evening 🌇

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