AZ.dev

TypeScript Essentials Cheat Sheet

TypeScript

The utility types, narrowing tricks, and compiler flags that come up every day in an ordinary TypeScript codebase.

12 cards | typescript: 5.0

Utility types

Make every property optional

type Draft = Partial<User>;

Required<T> goes the other way.

Keep a few fields, or drop a few

type Preview = Pick<User, "id" | "name">;
type Safe = Omit<User, "password">;

Type a lookup object

const byId: Record<string, User> = {};

Reading byId["missing"] types as User unless noUncheckedIndexedAccess is on.

Get a function's return type

type Result = ReturnType<typeof fetchUser>;

For an async function wrap it: Awaited<ReturnType<typeof fetchUser>>.

Narrowing

Write a type guard

function isCat(pet: Pet): pet is Cat {
  return "meow" in pet;
}

After if (isCat(pet)) the compiler treats pet as Cat in that branch.

Turn an array into a union of its values

const ROLES = ["user", "admin"] as const;
type Role = (typeof ROLES)[number];

Without as const the array is string[] and Role is just string.

Get the keys of an object as a union

type ConfigKey = keyof typeof config;

Generics

Constrain what a generic accepts

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

Works for strings, arrays, and anything else with a length.

Compiler

Type-check without emitting files

npx tsc --noEmit

Point it at another config with -p tsconfig.scripts.json.