๐ŸŽ“ A1Learner
๐Ÿ”

TypeScript Utility Types

Utility types build a new object type from an existing one. Each utility changes the properties of the type it receives.

Make every field optional with Partial

Partial takes an object type and makes every property optional. A draft can hold just one field and still compile.

interface Profile {
  name: string;
  age: number;
  city: string;
}

const draft: Partial<Profile> = { name: "Ada" };
console.log(draft);

Freeze a shape with Readonly

Readonly makes every property read-only. Reading the fields works as usual.

interface Profile {
  name: string;
  age: number;
  city: string;
}

const profile: Readonly<Profile> = { name: "Ada", age: 36, city: "London" };
console.log(profile.name, profile.age, profile.city);

Demand every field with Required

Required makes every property required. That includes properties marked optional in the first type. This object leaves out two fields, so the compiler refuses it.

interface Settings {
  theme: string;
  fontSize?: number;
  sidebar?: boolean;
}

const complete: Required<Settings> = { theme: "dark" };
console.log(complete);

Example

interface Profile {
  name: string;
  age: number;
  city: string;
}

function updateProfile(current: Profile, patch: Partial<Profile>): Profile {
  return { ...current, ...patch };
}

const profile: Profile = { name: "Ada", age: 36, city: "London" };
const updated = updateProfile(profile, { age: 37 });
console.log(updated);

Key points

  • Partial makes every property of a type optional
  • Required makes every property of a type required
  • Readonly makes every property of a type read-only
  • Assigning a new value to a Readonly property is refused by the compiler
  • A utility type creates a new type and leaves the original type unchanged

In this example, updateProfile takes a full Profile and a patch typed as Partial<Profile>. The patch holds only the age field. The spread copies the current fields first and then applies the patch. The logged object keeps the old name and city with the new age.

Note

Utility types work at type level only. They add no code to the emitted JavaScript

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does Partial<Profile> do to the Profile type?