Skip to content
tsCheatSheet
GitHub

Utility Types

Types built into TypeScript that help with common type manipulation.

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 optional
coordsPart.x = 10;

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

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 }`

Omit

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
};

Pick

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

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

Extracts return type from function type.

type CoordGenerator = () => { x: number; y: number };
const coord: ReturnType<CoordGenerator> = {
	x: 10,
	y: 20,
};

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,
};