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 makes all properties of an object optional.
interface Point { x: number; y: number; } let pointPart: Partial<Point> = {}; // `Partial` allows x and y to be optional pointPart.x = 10; |
Required makes all properties of an object mandatory.
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 is a shortcut for defining an object type with specific key and value types.
const nameAgeMap: Record<string, number> = { ‘Alice’: 21, ‘Bob’: 25 }; |
Record<string, number> is equivalent to { [key: string]: number }.
Omit removes specific keys from an object type.
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 keeps only the specified keys in an object type, removing the rest.
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 }; |