Curriculum
Course: TypeScript
Login
Text lesson

TS Utility Types

TypeScript provides many built-in types for common type manipulations, commonly known as utility types.

This chapter will cover the most widely used utility types.

Partial

Partial makes all properties of an object optional.

Example

interface Point {
  x: number;
  y: number;
}

let pointPart: Partial<Point> = {}; // `Partial` allows x and y to be optional
pointPart.x = 10;

Required

Required makes all properties of an object mandatory.

Example

interface Car {
  make: string;
  model: string;
  mileage?: number;
}

let myCar: Required<Car> = {
  make: ‘Ford’,
  model: ‘Focus’,
  mileage: 12000 // `Required` forces mileage to be defined
};

Record

Record is a shortcut for defining an object type with specific key and value types.

Example

const nameAgeMap: Record<string, number> = {
  ‘Alice’21,
  ‘Bob’25
};

Record<string, number> is equivalent to { [key: string]: number }.

Omit

Omit removes specific keys from an object type.

Example

interface Person {
  name: string;
  age: number;
  location?: string;
}

const bob: Omit<Person, ‘age’ | ‘location’> = {
  name: ‘Bob’
  // `Omit` has removed age and location from the type and they can’t be defined here
};

Pick

Pick keeps only the specified keys in an object type, removing the rest.

Example

interface Person {
  name: string;
  age: number;
  location?: string;
}

const bob: Pick<Person, ‘name’> = {
  name: ‘Bob’
  // `Pick` has only kept name, so age and location were removed from the type and they can’t be defined here
};