I came across this typescript challenge MyReadonly2. Here is my original solution:
// doesn't work as `Exclude` could potentially change the existing `readonly` modifier in the object
type MyReadonly2<T, K extends keyof T = keyof T> = { [P in Exclude<keyof T, K>]: T[P] } & { readonly [P in K]: T[P] }
Here is one of the correct answers:
type MyReadonly2<T, K extends keyof T = keyof T> = Omit<T, K> & { readonly [P in K]: T[P] }
Basically both approaches have the same idea, but how can I make sure I'm not changing the object's readonly modifier when I copy its members? The only difference from Omit
is just the type constraint on K:
type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }
Why does it make a difference?