TypeScript ยท Chapter 29 of 44

TypeScript Utility Types Overview

TypeScript includes a set of built-in utility types that transform existing types into new ones, saving you from writing repetitive type definitions by hand. They live in the global scope, so no import is needed.

Common utility types include `Partial`, `Pick`, `Omit`, `Record`, `Readonly`, and `Required`. Each takes one or more type arguments and produces a new, transformed type based on them.

Syntax
type PartialUser = Partial<User>;
type ReadonlyUser = Readonly<User>;

Why use utility types?

Instead of manually rewriting a similar type with small tweaks, utility types let you derive it directly from an existing type, keeping your types in sync automatically when the source changes.

Common utility types

`Partial<T>` makes all properties optional. `Required<T>` makes all properties required. `Readonly<T>` makes all properties readonly. Later lessons cover Pick, Omit and Record in depth.

Example 1 (typescript)
interface User {
  name: string;
  age: number;
}
type PartialUser = Partial<User>;
const update: PartialUser = { age: 31 };
console.log(update);
Output
{ age: 31 }

Partial<User> makes both name and age optional, so update can include just one property.

Example 2 (typescript)
interface User {
  name: string;
  age: number;
}
const frozen: Readonly<User> = { name: "Al", age: 40 };
// frozen.age = 41; // Error
console.log(frozen);
Output
{ name: 'Al', age: 40 }

Readonly<User> makes every property immutable after creation.

Key points

  • Utility types transform existing types into new ones.
  • They are globally available without any import.
  • Partial makes all properties optional; Required makes them all mandatory.
  • Readonly makes every property in a type immutable.
๐Ÿ’ก Note: Utility types keep derived types automatically in sync with their source type as it evolves.

๐Ÿ“ Quick Quiz

1. What does Partial<T> do?

2. Do you need to import utility types like Partial?

3. What does Readonly<T> do?