Partial readonly

Example of Readonly use

We already solved the challenge with readonly (see Readonly under the hood). Today we want to apply readonly modifier only to the specified keys (Readonly 2).

Combination of 2 challenges

Again, as for previous challenge Omit under the hood, we have a combination of challenges that we already did:

  1. We already learnt how to apply readonly modifier to the keys:

Readonly solution

  1. We also need to pick specified keys:

Pick solution

  1. And we need to have excluded keys without readonly modifier:

Omit solution

The algorithm is:

  1. Pick keys we want to make readonly
  2. Make picked keys readonly
  3. Add the rest (or excluded) keys without changes

Solution, version 1

If you check the current solution, you see that you cannot use Pick and Omit if K is not part of keyof T. Let’s fix that:

Solution, version 2

But still we expect to have all keys by default if we don’t specify K. So the final solution is:

Final solution

As usual, the solution is in Playground 💻

Have a nice weekend 🌤

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