Cheatsheet for TypeScript Utility Types

Quick start on Partial, Required, Readonly, Record, Pick, Omit, Exclude, Extract, Parameters, etc.

Photo by Akira on Unsplash

Partial<T>

class StateStore<T> {
constructor(public current: T) { }
update(next: Partial<T>) {
this.current = { ...this.current, ...next };
}
}
const state = new StateStore({ x: 0, y: 0 });
state.update({ y: 123 });
console.log(state.current); // { x: 0, y: 123 }

Required<T>

type Example = {
a?: string,
b?: number,
}

const example: Required<Example> = { a: "a" }
// Property 'b' is missing in type '{ a: string; }' but required in type 'Required<Example>'.

Readonly<T>

type Example = {
a: string,
b: number,
}
function makeReadonly<T>(object: T): Readonly<T> {
return Object.freeze({ ...object });
}
const example: Example = { a: "a", b: 1 }

const readonlyExample = makeReadonly(example);
readonlyExample.a = "no readonly"; // Error: readonly

Record<K, T>

interface CatInfo {
age: number;
breed: string;
}
type CatName = “miffy” | “boris”const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: “Persian” },
boris: { age: 5, breed: “Maine Coon” },
};
cats.boris; // const cats: Record<CatName, CatInfo>

Pick<T, Keys>

type Point3D = {
x: number,
y: number,
z: number,
};
type Point2D = Pick<Point3D, 'x' | 'y'>;
// type Point2D = {
x: number;
y: number;
}

Omit<T, Keys>

type Point3D = {
x: number,
y: number,
z: number,
};

type Point2D = Omit<Point3D, 'z'>;
// type Point2D = {
x: number;
y: number;
}

Exclude<Union, ExcludedUnion>

type flat3D = 'x' | 'y' | 'z';
type flat2D = Exclude<flat3D, 'z'>
// 'x' | 'y'

Extract<Union, ExtractedUnion>

type flat3D = 'x' | 'y' | 'z';
type flat2D = Extract<flat3D, 'z'>
// 'z'
type flatD= Extract<flat3D, flat2D>; 
// 'z'
type flatD= flat3D & flat2D
// 'z'

NonNullable<T>

type StrOrNullOrUndefined = string | null | undefined;
type Str = NonNullable<StrOrNullOrUndefined>;

Parameters<Function>

function f1(a: number, b: number) {
return a + b;
}
type f1Params = Parameters<typeof f1>; //[number, number]
type f2 = Parameters<(s: string) => void> // [string]

ConstructorParameters<ClassConstructor>

class Point2D {
private x: number;
private y: number;
constructor( x: number, y: number ) {
this.x = x;
this.y = y;
}
}
type point2DConstructor = ConstructorParameters<typeof Point2D>
// [number, number]
const point2DConstructorExample: ConstructorParameters<typeof Point2D>[0] = 0

ReturnType<Function>

function f1(a: number, b: number) {
return a + b;
}
type f1ReturnType = ReturnType<typeof f1>;
//type f1ReturnType = number

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store