8 - Readonly 2
Author: VarunMendreCreated Sep 14, 2026Updated Sep 14, 2026
Labelsanswer8en
// MyReadonly2<T, K>: Makes properties in K readonly, rest stay mutable.
// K defaults to keyof T (all keys) when omitted, behaving like Readonly<T>.
//
// Uses intersection (&) to split keys into two mapped types:
// 1. Keys IN K → readonly
// 2. Keys NOT in K → mutable
//
// A single mapped type can't conditionally apply `readonly` per key,
// so we intersect two filtered mapped types instead.
type MyReadonly2<T, K extends keyof T = keyof T> = {
readonly [P in keyof T as P extends K ? P : never] : T[P]
} & {
[P in keyof T as P extends K ? never : P]: T[P]
}
Source: type-challenges/type-challenges