beraliv

Conditionally readonly object type in TypeScript

Example of Readonly use
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
Readonly solution
  1. We also need to pick specified keys:
Pick solution
Pick solution
  1. And we need to have excluded keys without readonly modifier:
Omit solution
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
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
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
Final solution

As usual, the solution is in Playground 💻

Have a nice weekend 🌤

typescript

Comments

Alexey Berezin profile image

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