Skip to content

TypeScript Cheat Sheet

Types, generics, utility types, and narrowing.

A compact reference for everyday TypeScript — the type syntax, the built-in utility types, and the narrowing patterns that make the compiler work for you rather than fighting it.

The utility-types section saves the most time: `Partial`, `Pick`, `Omit`, and `Record` express common transformations of a type without redefining it, and reaching for them is a sign of idiomatic TypeScript.

Basic types

let n: number; let s: string; let b: booleanPrimitive annotations.
let xs: string[] · Array<string>Array of strings (two syntaxes).
let t: [string, number]Tuple — fixed-length, typed positions.
type Dir = 'n' | 's' | 'e' | 'w'Union / string-literal type.
let u: unknown · let a: anyunknown is safe (must narrow); avoid any.

Interfaces & types

interface User { id: number; name: string }Object shape (extendable, mergeable).
type User = { id: number; name: string }Type alias — also for unions/primitives.
interface Admin extends User { role: string }Extend an interface.
name?: string · readonly id: numberOptional and read-only members.
type Id = User['id']Index into a type to reuse a member type.

Generics

function first<T>(xs: T[]): TGeneric function — T inferred from args.
interface Box<T> { value: T }Generic type.
<T extends { id: number }>Constrain a type parameter.
function get<T, K extends keyof T>(o: T, k: K)Key-safe property access.

Utility types

Built-in transformations of an existing type.

Partial<T> · Required<T>Make all members optional / required.
Pick<T, K> · Omit<T, K>Keep only, or drop, listed keys.
Record<K, V>Object type with keys K and values V.
Readonly<T>Make all members read-only.
ReturnType<F> · Awaited<T>A function’s return type; unwrap a Promise.

Narrowing

typeof x === 'string'Narrow primitives.
x instanceof ErrorNarrow class instances.
'id' in objNarrow by property presence.
if (x == null) returnGuard against null and undefined together.
function isX(v): v is XCustom type guard (predicate return type).

Frequently asked questions

When should I use interface vs type in TypeScript?

Use `interface` for object shapes you may extend or that describe a public API — interfaces support declaration merging and `extends`. Use `type` when you need unions, intersections, tuples, mapped types, or aliases for primitives. For plain object shapes the two are largely interchangeable; pick one and stay consistent.

What is the difference between unknown and any?

`any` disables type checking — you can do anything with the value and the compiler stays silent, which defeats the point of types. `unknown` is the type-safe counterpart: you can hold any value, but you must narrow it (with `typeof`, a guard, etc.) before using it, so mistakes are caught.