Utility Types
Types built into TypeScript that help with common type manipulation.
Partial
Section titled “Partial”Makes all properties in an object optional.
interface Coords { x: number; y: number;}
let coordsPart: Partial<Coords> = {}; // `Partial` allows x// and y to be optionalcoordsPart.x = 10;
Required
Section titled “Required”Makes all properties in an object required.
interface Vehicle { make: string; model: string; mileage?: number;}
let myCar: Required<Vehicle> = { make: 'Honda', model: 'Civic', mileage: 30000, // `Required` forces mileage to be defined};
Record
Section titled “Record”Creates an object type whose property keys are Keys and whose property values are Type.
const ageNameMap: Record<string, number> = { Matt: 20, Michael: 24,};//`Record<string, number>` is the same as `{ [key: string]: number }`
From an object type., remove keys.
interface Employee { name: string; age: number; location?: string;}
const matt: Omit<Employee, 'age' | 'location'> = { name: 'Matt', // `Omit` has removed age and location from the type // and they can't be defined here};
Removes all keys, except those speficied (the opposite of Omit
).
const Michael: Pick<Employee, 'name'> = { name: 'Michael', // `Pick` has only kept name, so age and location // were removed from the type and they can't be defined here};
Exclude
Section titled “Exclude”Removes types from a union.
type Primitive = string | number | boolean;const value3: Exclude<Primitive, string> = true; // a string cannot// be used since Exclude removed it from the type.
Return type
Section titled “Return type”Extracts return type from function type.
type CoordGenerator = () => { x: number; y: number };const coord: ReturnType<CoordGenerator> = { x: 10, y: 20,};
Parameters
Section titled “Parameters”Extracts the parameters types from a function (as an array).
type CoordPrinter = (p: { x: number; y: number }) => void;const coord2: Parameters<CoordPrinter>[0] = { x: 10, y: 20,};