Skip to main content
Quick Reference

TypeScript Cheatsheet

TypeScript on one page — strict setup, unions and literals, objects, functions, arrays and generics, narrowing, utility types, classes, modules, and the traps that show up when strict mode is on.

10 sections 8 tables 20 code snippets

Project & Everyday Types

Start strict

npm install -D typescript
npx tsc --init
npx tsc --noEmit
npx tsc --watch

A typed value

const title: string = "TypeScript";
let score: number = 42;
const ok: boolean = true;
const missing: null = null;

function greet(name: string): string {
  return "Hello, " + name;
}

Turn these on

tsconfigWhy
"strict": trueEnables null checks, implicit any bans, and stricter class fields
"noUncheckedIndexedAccess": truearr[i] becomes T | undefined
"exactOptionalPropertyTypes": trueOptional means “missing”, not “set to undefined”
"noEmitOnError" is default for tsc --noEmitCheck types without writing JavaScript

TypeScript erases types at compile time. A cast does not convert a value. If the runtime value is wrong, the program still runs the wrong value.

Unions, Literals & Narrowing

Union and literal

type Id = string | number;
type Status = "draft" | "live";

function label(status: Status): string {
  if (status === "draft") return "Draft";
  return "Live";
}

unknown before you trust it

function lengthOf(value: unknown): number {
  if (typeof value === "string") return value.length;
  if (Array.isArray(value)) return value.length;
  return 0;
}

What each type means

TypeMeaning
string | numberOne of those types. Narrow before using a method
"draft" | "live"Only those strings. Typos are errors
unknownA value you have not checked. The safe top type
anyTurns checking off. Avoid it
neverA value that cannot exist. Exhaustive switches use it
voidA function that returns nothing useful

Objects, Interfaces & Aliases

interface and type

interface User {
  readonly id: string;
  name: string;
  bio?: string;
}

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

const user: User = { id: "u1", name: "Ravi" };

Intersection and index

type WithDate = User & { createdAt: Date };

type Scores = { [subject: string]: number };

type Course = {
  title: string;
  tags: string[];
};

interface vs type

interfacetype
Object shapeYesYes
UnionNoA | B
Extendextends&
Declaration mergingYes. Two interfaces with one name combineNo
Default choicePublic object contractsUnions, tuples, mapped types

Functions

Parameters and returns

function area(width: number, height = 1): number {
  return width * height;
}

const shout = (text: string): string => text.toUpperCase();

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

Optional, rest, overloads

function pad(text: string, width?: number): string {
  return text.padStart(width ?? 0);
}

function sum(...nums: number[]): number {
  return nums.reduce((total, n) => total + n, 0);
}

Call shapes

FormMeaning
height = 1Optional by a default. Type is still number
width?: numberCaller may omit it. Type is number | undefined
...nums: number[]Rest parameter. Caller passes a list
<T>(items: T[])Generic. T is chosen from the argument
voidReturn value should be ignored

Arrays, Tuples & Generics

Arrays and tuples

const tags: string[] = ["ts", "js"];
const pair: [string, number] = ["age", 21];

const point = [10, 20] as const;

A small generic

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

const name = pick({ name: "Ada", age: 20 }, "name");

Constraints

FormMeaning
T[] or Array<T>A list of T
[string, number]Fixed length and fixed types per slot
as constWidest literal type, and the array becomes readonly
K extends keyof TK must be a key of T
T extends { id: string }T must have at least an id
Record<string, number>An object whose values are numbers

Narrowing & Discriminated Unions

typeof, in, instanceof

function print(value: Date | string): string {
  if (value instanceof Date) return value.toISOString();
  return value;
}

function hasName(value: object): value is { name: string } {
  return "name" in value && typeof value.name === "string";
}

Discriminant

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rect":
      return shape.width * shape.height;
  }
}

After the switch handles every kind, shape is never. Add a new variant and TypeScript reports the missing case. That is the point of a discriminant.

Utility Types

Change a shape

interface User {
  id: string;
  name: string;
  email: string;
}

type Draft = Partial<User>;
type PublicUser = Omit<User, "email">;
type Preview = Pick<User, "id" | "name">;

Check a value against a type

const routes = {
  home: "/",
  blog: "/blog",
} as const satisfies Record<string, string>;

type RouteName = keyof typeof routes;

Built-ins you will actually use

UtilityResult
Partial<T>Every field optional
Required<T>Every field required
Readonly<T>Fields cannot be reassigned
Pick<T, K>Only those keys
Omit<T, K>All keys except those
Record<K, V>An object of keys K and values V
ReturnType<typeof fn>Whatever the function returns
Parameters<typeof fn>The parameter list as a tuple

Classes

Parameter properties

class User {
  constructor(
    public readonly id: string,
    private name: string,
  ) {}

  greet(): string {
    return "Hi, " + this.name;
  }
}

implements

interface Greeter {
  greet(): string;
}

class Bot implements Greeter {
  greet(): string {
    return "beep";
  }
}

Visibility

KeywordWho can use it
publicAnyone. This is the default
protectedThis class and subclasses
privateThis class, checked only by TypeScript
#nameRuntime private field. JavaScript enforces it
readonlyAssign in the constructor, then stop
abstractSubclass must implement it. No new on the base

Modules & Imports

Export and import

export type UserId = string;
export interface User { id: UserId; name: string }

export function createUser(name: string): User {
  return { id: "u1", name };
}

Type-only import

import { createUser } from "./user";
import type { User } from "./user";

const user: User = createUser("Ada");

import type is erased completely. Use it so a type import cannot become a runtime import and pull a module into the browser by accident.

Interview Traps

Traps worth memorising

TrapWhat happensPrefer
anyThe checker stopsunknown, then narrow
as User on JSONNo runtime check. Bad data still passesA function that validates and returns User
user!.nameThe ! silences null. It can still throwCheck user first
arr[0].name under strict index accessIndex can be undefinedCheck the element, or enable the flag on purpose
Numeric enumReverse mapping and a runtime objectA string union, or a string enum
Two interfaces, same nameThey merge. A typo becomes a new fieldOne interface per name, or use type
Excess property on a variableExtra fields are allowed once the value is not a fresh literalDo not rely on excess checks for validation
private fieldOnly the compiler hides it#field when JavaScript must hide it
object vs a shapeobject is almost every non-primitiveWrite the fields you need
Optional bio?: stringThe key may be missingRead it as string | undefined
Generic defaults to {} in old codeConstraint is too wideConstrain with extends
Comparing types with ===Types do not exist at runtimeCompare values, or use a discriminant

Parse, do not cast

function asUser(value: unknown): User {
  if (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    "name" in value
  ) {
    return { id: String(value.id), name: String(value.name) };
  }
  throw new Error("not a user");
}

Exhaustive switch

function assertNever(value: never): never {
  throw new Error("unexpected " + String(value));
}

How to use this page: turn "strict": true on, then retype one function with a union and a switch. If a branch is missing, the never check should fail the build. That is the habit worth keeping.