Skip to content
jshacks.dev
TypeScript

TypeScript Cheat Sheet

A TypeScript 6 cheat sheet of daily syntax: basic types, unions, generics, narrowing, utility types, classes and the compiler flags worth turning on.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm and JavaScript logos.

This TypeScript cheat sheet collects the syntax people look up most often, grouped by task, with the type the compiler infers or the error it reports. It targets TypeScript 6.x and applies unchanged to the native TypeScript 7 compiler. Every entry says when not to use it, because a cheat sheet that lists only the happy path teaches the wrong habits. The authoritative reference is the TypeScript handbook and the TSConfig reference.

Basic types and annotations

SyntaxMeaningAvoid when
let n: numberA number, including NaN and InfinityYou can initialize it and let inference work
let s: stringAny stringThe set of strings is small: use a union of literals
let b: booleantrue or false
let big: bigintAn arbitrary-precision integerYou need to mix with number without conversion
let a: number[]An array of numbersThe length is fixed: use a tuple
let t: [string, number]A tuple of exactly two itemsThe items are not positional
let u: unknownA value you must check before useYou can name the type
let a: anyOpts out of checkingAlmost always
let v: voidNo return value
let x: neverA value that cannot occur
basics.tsTypeScript
const port = 3000;
let name = "api";
const tags: string[] = [];
const pair: [string, number] = ["retries", 3];

tags.push("a");
console.log(port, name, tags, pair);
Text
3000 api [ 'a' ] [ 'retries', 3 ]

const port is inferred as the literal 3000, while let name is inferred as string. Annotate when the initializer cannot say what you mean, such as an empty array.

Unions, literals and narrowing

unions.tsTypeScript
type Status = "idle" | "loading" | "done";
type Id = string | number;

function show(id: Id): string {
  if (typeof id === "string") {
    return id.toUpperCase();
  }
  return id.toFixed(1);
}

console.log(show("ab"), show(4));
Text
AB 4.0
Narrowing toolExampleWorks on
typeoftypeof x === "string"Primitives
instanceofx instanceof DateClass instances
in"name" in xObject unions
Equalityx === "idle"Literal unions
Truthinessif (x)Removing null and undefined, and also 0 and ""
Discriminantshape.kind === "circle"Tagged unions
User guardx is DogAnything you can check yourself

Truthiness narrowing also removes 0 and the empty string, which is rarely what you want for a number. Compare with !== undefined instead.

Objects, interfaces and type aliases

objects.tsTypeScript
interface User {
  readonly id: number;
  name: string;
  email?: string;
}

type Point = { x: number; y: number };

const user: User = { id: 1, name: "Ada" };
const origin: Point = { x: 0, y: 0 };
console.log(user, origin);
Text
{ id: 1, name: 'Ada' } { x: 0, y: 0 }

readonly blocks assignment through that property, and ? makes it optional, which adds undefined to its type. Use interface for object shapes that can be extended and type for unions, tuples and mapped types.

Functions

functions.tsTypeScript
function add(a: number, b: number = 1): number {
  return a + b;
}

const log = (message: string, ...rest: unknown[]): void => {
  console.log(message, ...rest);
};

type Handler = (event: string) => void;

log("sum", add(2), add(2, 5));
Text
sum 3 7

Annotate parameters and exported return types. Inference handles local callbacks, so items.map((item) => item.id) needs no annotation.

Generics

generics.tsTypeScript
function first<T>(items: T[]): T | undefined {
  return items[0];
}

function pick<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

console.log(first([10, 20]), pick({ id: 7, name: "x" }, "name"));
Text
10 x

K extends keyof T limits the key to real property names, so pick(obj, "nope") is a compile error. Give a type parameter a default with <T = string>. Do not add a generic that appears only once in the signature: it is not linking anything, and an ordinary type does the same job.

Utility types

UtilityResultExample
Partial<T>Every property optionalUpdate payloads
Required<T>Every property required
Readonly<T>Every property readonlyFrozen config
Pick<T, K>Only the listed keysPick<User, "id">
Omit<T, K>Everything but the listed keysOmit<User, "email">
Record<K, V>An object with keys K, values VLookup tables
ReturnType<F>A function's return type
Parameters<F>A function's parameter tuple
Awaited<T>The type a promise resolves to
NonNullable<T>Removes null and undefined
utility.tsTypeScript
interface User {
  id: number;
  name: string;
  email: string;
}

type Patch = Partial<Omit<User, "id">>;
const patch: Patch = { name: "Grace" };
console.log(patch);
Text
{ name: 'Grace' }

Classes

classes.tsTypeScript
class Counter {
  #count = 0;

  constructor(private readonly step: number = 1) {}

  increment(): number {
    this.#count += this.step;
    return this.#count;
  }
}

const counter = new Counter(2);
counter.increment();
console.log(counter.increment());
Text
4

private is checked only by the compiler, while #count is a real private field at runtime. Prefer # when the privacy has to hold for callers in plain JavaScript.

Assertions and satisfies

SyntaxUse it for
value as TA claim the compiler cannot verify
value!Removing null and undefined, at your risk
value satisfies TChecking against T while keeping the inferred type
as constLiteral, readonly inference

Compiler flags worth having

FlagWhat it catches
strictThe whole strict family, on by default in new projects
noUncheckedIndexedAccessarray[i] may be undefined
exactOptionalPropertyTypes? means absent, not undefined
noImplicitOverrideRequires override on overriding methods
verbatimModuleSyntaxKeeps import type honest
isolatedModulesSafe for single-file transpilers

Common errors

MessageUsual cause
TS2322 Type X is not assignable to type YA value of the wrong shape
TS2339 Property does not exist on typeTypo, or a union not narrowed
TS2345 Argument of type X is not assignableWrong argument at a call
TS18048 is possibly undefinedA missing null check
TS7006 Parameter implicitly has an any typeA missing annotation under strict

How to use this sheet

Use it as a prompt for the right tool, then read the handbook page for the exact rules. If a type is getting complicated, say what the function promises in a sentence, then write the smallest type that states it. Most cleverness in type signatures is a sign that the data model needs a simpler shape, not a better utility type.

Reading the compiler's answers

A cheat sheet helps you write, but most of the time with TypeScript goes to reading what the compiler says back. Three habits make those messages shorter to read. First, start at the last line of a multi-line error. The first line states the symptom, such as "Type X is not assignable to type Y", and the indented lines below it narrow down which property or which union member failed. The deepest line is usually the actual disagreement.

Second, hover the variable in your editor before you change anything. The hover shows the inferred type, and about half of all confusing errors are explained by a type that is wider or narrower than you assumed. A let declaration widens a literal to string. An array literal of mixed values becomes a union array. An object returned from a function loses a literal unless you used as const.

Third, when an error mentions a type you did not write, find where it came from. A call to a generic function, a mapped type or a utility type produces a derived type, and the fix is usually at the source: a missing constraint, a missing as const, or a function that returns a looser type than it should.

When the sheet is not enough

Some situations need more than syntax. If a type needs three levels of conditional types to express, check whether the runtime data could be modeled as a tagged union instead, which both TypeScript and your teammates understand at a glance. If a function needs many overloads, check whether one generic signature with a constraint covers them. If you keep asserting with as, check whether the value should be validated once at the boundary, so that everything inside the program works with a type that was proven rather than claimed.

The most useful setting for learning is a strict configuration from the first day. Turning strict on late in a project's life produces hundreds of errors at once, and turning it on at the start produces a few at a time, each next to the code that caused it.

Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.