Sikau

TypeScript · Day 17 · about 25 min

Utility types

Partial, Pick, Omit, Record, Readonly.

Types from types

Updating a user only needs *some* fields. A public profile shows only *some* properties. Instead of copying type definitions, utility types build new types from existing ones.

The everyday five

interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}

type UserUpdate = Partial<User>;
type PublicUser = Omit<User, "password" | "email">;
type Login = Pick<User, "email" | "password">;
type FrozenUser = Readonly<User>;
type ScoreBoard = Record<string, number>;

function update(user: User, changes: UserUpdate): User {
  return { ...user, ...changes };
}
const board: ScoreBoard = { asha: 90, ram: 75 };
const pub: PublicUser = { id: 1, name: "Asha", password: "x" };

The rest of this lesson

  • Utility types in real codeexplain
  • Readonly and Requiredexplain
  • Which type?predict
  • Pick the utilitymatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript