Bitpath

Boss lesson · Unit 02

Utility Types by Hand

Rebuild Partial, Readonly, Pick, Omit and Record, then type an update function

13 exercisesabout 3 min

What you practise

  • Mapped types
  • Partial, Readonly, Pick, Omit and Record rebuilt and then used to type an update function

Try a question from this lesson

Pick one

Rebuilding Readonly: the modifier goes in front of the key. Which line does the compiler reject?

TypeScript
type RO<T> = {
  readonly [K in keyof T]: T[K];
};
interface User {
  id: number; tags: string[];
}
const u: RO<User> = { id: 1, tags: [] };
u.tags.push("x");
u.id = 2;
Hint

One line replaces a property of u. The other changes something a property points to.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Mapped types

A mapped type is a loop over keys, run by the compiler. [K in keyof T] visits each property name of T, and the right-hand side says what type that property gets.

It is a dict comprehension over a type: {k: bool for k in T}. Put T[K] on the right to keep each property's own type.

TypeScript
type Flags<T> = {
  [K in keyof T]: boolean;
};
interface User {
  id: number;
  name: string;
}
type Seen = Flags<User>;
// { id: boolean; name: boolean }

const s: Seen = { id: true, name: false };

Concept

Pick and Omit

A mapped type need not visit every key. Pick loops over a chosen subset K, and the constraint K extends keyof T guarantees the subset is real.

Omit is Pick with the unwanted keys removed first. Exclude<A, B> is the built-in that drops from union A every member found in B.

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

interface User {
  id: number; name: string; age: number;
}
const a: MyPick<User, "id"> = { id: 1 };
const b: MyOmit<User, "age"> = {
  id: 1, name: "Ada",
};

10 more exercises in the app

  • 2× type the answer
  • 3× fill the blanks
  • 4× multiple choice
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy