[Typescript] 122. Hard - Mutable Keys

Implement the advanced util type MutableKeys, which picks all the mutable (not readonly) keys into a union.

For example:

type Keys = MutableKeys<{ readonly foo: string; bar: number }>;
// expected to be “bar”
 
/* _____________ Your Code Here _____________ */

type MutableKeys<T> = keyof {
  [Key in keyof T as Equal<Pick<T, Key>, Readonly<Pick<T, Key>>> extends true ? never: Key]: T[Key]
}

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<MutableKeys<{ a: number; readonly b: string }>, 'a'>>,
  Expect<Equal<MutableKeys<{ a: undefined; readonly b: undefined }>, 'a'>>,
  Expect<Equal<MutableKeys<{ a: undefined; readonly b?: undefined; c: string; d: null }>, 'a' | 'c' | 'd'>>,
  Expect<Equal<MutableKeys<{}>, never>>,
]

 

posted @ 2022-11-30 14:48  Zhentiw  阅读(26)  评论(0编辑  收藏  举报