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;
} 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;
} 📦 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[];
}; 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);
} 📚 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"); 🔎 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. 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 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";
}
} 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. 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. |