CodePark/ questions / Utility types
START PRACTICINGPRACTICE
Frontend question · TypeScript › Utility types

Implement Partial, Pick and Omit yourself.

type MyPartial<T> = { [K in keyof T]?: T[K] };

type MyPick<T, K extends keyof T> = { [P in K]: T[P] };

type MyOmit<T, K extends keyof any> = MyPick<T, Exclude<keyof T, K>>;

All three are mapped types: types that build a new object type by looping over a set of keys.

MyPartial loops over every key of T with [K in keyof T]. It adds the ? modifier and keeps the value type with T[K].

MyPick limits K to keys of T. It then loops only over those keys, so the result has just the chosen properties.

MyOmit is built from the others:

  • Exclude<keyof T, K> gives the keys that remain.
  • MyPick keeps those keys.

Like the built-in Omit, MyOmit limits K to keyof any, which is string | number | symbol. So you can pass keys that do not exist on T. This makes Omit less strict than Pick, which only accepts real keys.

  • These are mapped types that loop over keyof T and keep the value type T[K].
  • Partial adds the ? modifier to every property.
  • Pick loops over a chosen subset of keys, with K extends keyof T.
  • Omit is Pick of Exclude<keyof T, K>.
  • The built-in Omit does not require K to be keys that exist on T.