Partial, Readonly, Record, and Pick

Partial and Readonly, as described earlier, are very useful constructs.You can use them to describe some common JS routines like:

  1. function assign<T>(obj: T, props: Partial<T>): void;
  2. function freeze<T>(obj: T): Readonly<T>;

Because of that, they are now included by default in the standard library.

We’re also including two other utility types as well: Record and Pick.

  1. // From T pick a set of properties K
  2. declare function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K>;
  3. const nameAndAgeOnly = pick(person, "name", "age"); // { name: string, age: number }
  1. // For every properties K of type T, transform it to U
  2. function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>
  3. const names = { foo: "hello", bar: "world", baz: "bye" };
  4. const lengths = mapObject(names, s => s.length); // { foo: number, bar: number, baz: number }