TypeScript Cheat Sheet
Basic Types
Section titled “Basic Types”let isDone: boolean = false;let count: number = 42;let name: string = "hello";let list: number[] = [1, 2, 3];let tuple: [string, number] = ["hello", 10];let anything: any = 4;let unknown: unknown = 4; // Safer than anylet nothing: void = undefined;let n: null = null;let u: undefined = undefined;let never: never; // Function that never returnsType Inference
Section titled “Type Inference”let x = 3; // inferred as numberconst y = "hello"; // inferred as "hello" (literal type)let arr = [1, 2, 3]; // inferred as number[]Interfaces & Types
Section titled “Interfaces & Types”// Interfaceinterface User { readonly id: number; name: string; email?: string; // Optional [key: string]: unknown; // Index signature}
// Type aliastype Point = { x: number; y: number;};
// Union typestype Status = "pending" | "success" | "error";type Result = string | number;
// Intersection typestype Admin = User & { permissions: string[] };
// Extending interfacesinterface Employee extends User { department: string;}Functions
Section titled “Functions”// Typed functionfunction greet(name: string): string { return `Hello, ${name}`;}
// Arrow functionconst add = (a: number, b: number): number => a + b;
// Optional and default parametersfunction log(msg: string, level: string = "info"): void {}
// Rest parametersfunction sum(...numbers: number[]): number { return numbers.reduce((a, b) => a + b, 0);}
// Function typestype Callback = (data: string) => void;type AsyncFn = (id: number) => Promise<User>;
// Overloadsfunction parse(input: string): number;function parse(input: number): string;function parse(input: string | number): string | number { return typeof input === "string" ? parseInt(input) : input.toString();}Generics
Section titled “Generics”// Generic functionfunction identity<T>(arg: T): T { return arg;}
// Generic interfaceinterface Container<T> { value: T;}
// Generic classclass Queue<T> { private items: T[] = []; enqueue(item: T): void { this.items.push(item); } dequeue(): T | undefined { return this.items.shift(); }}
// Generic constraintsfunction getLength<T extends { length: number }>(arg: T): number { return arg.length;}
// Multiple type parametersfunction map<T, U>(arr: T[], fn: (item: T) => U): U[] { return arr.map(fn);}
// Default type parametersinterface Response<T = any> { data: T; status: number;}Utility Types
Section titled “Utility Types”interface User { id: number; name: string; email: string;}
Partial<User>; // All properties optionalRequired<User>; // All properties requiredReadonly<User>; // All properties readonlyPick<User, "id" | "name">; // Only id and nameOmit<User, "email">; // Everything except emailRecord<string, number>; // { [key: string]: number }Exclude<"a" | "b", "a">; // "b"Extract<"a" | "b", "a" | "c">; // "a"NonNullable<string | null>; // stringReturnType<typeof fn>; // Return type of functionParameters<typeof fn>; // Tuple of parameter typesAwaited<Promise<string>>; // stringType Guards
Section titled “Type Guards”// typeoffunction process(x: string | number) { if (typeof x === "string") { return x.toUpperCase(); } return x * 2;}
// instanceoffunction handle(err: Error | string) { if (err instanceof Error) { return err.message; } return err;}
// in operatorinterface Cat { meow(): void;}interface Dog { bark(): void;}
function speak(pet: Cat | Dog) { if ("meow" in pet) { pet.meow(); } else { pet.bark(); }}
// Custom type guardfunction isString(x: unknown): x is string { return typeof x === "string";}Classes
Section titled “Classes”class Animal { private _name: string; protected age: number; public readonly species: string; static count = 0;
constructor(name: string, age: number, species: string) { this._name = name; this.age = age; this.species = species; Animal.count++; }
get name(): string { return this._name; }
set name(value: string) { this._name = value; }
speak(): void { console.log(`${this._name} makes a sound`); }}
// Inheritanceclass Dog extends Animal { constructor(name: string, age: number) { super(name, age, "dog"); }
override speak(): void { console.log(`${this.name} barks`); }}
// Abstract classabstract class Shape { abstract area(): number; describe(): string { return `Area: ${this.area()}`; }}// Numeric enumenum Direction { Up, // 0 Down, // 1 Left, // 2 Right, // 3}
// String enumenum Status { Pending = "PENDING", Success = "SUCCESS", Error = "ERROR",}
// Const enum (inlined at compile time)const enum Color { Red, Green, Blue,}Mapped Types
Section titled “Mapped Types”// Make all properties optionaltype Optional<T> = { [P in keyof T]?: T[P];};
// Make all properties nullabletype Nullable<T> = { [P in keyof T]: T[P] | null;};
// Template literal typestype EventName<T extends string> = `on${Capitalize<T>}`;type ClickEvent = EventName<"click">; // "onClick"Conditional Types
Section titled “Conditional Types”type IsString<T> = T extends string ? true : false;
type Flatten<T> = T extends Array<infer U> ? U : T;type Str = Flatten<string[]>; // stringtype Num = Flatten<number>; // number
// Distributive conditional typestype ToArray<T> = T extends any ? T[] : never;type StrOrNumArray = ToArray<string | number>; // string[] | number[]Module Patterns
Section titled “Module Patterns”// Named exportsexport const PI = 3.14;export function add(a: number, b: number): number { return a + b;}export interface User { name: string;}
// Default exportexport default class MyClass {}
// Re-exportexport { something } from "./module";export * from "./module";export * as utils from "./utils";
// Import types onlyimport type { User } from "./types";Assertion & Casting
Section titled “Assertion & Casting”// Type assertionconst el = document.getElementById("app") as HTMLDivElement;const el2 = <HTMLDivElement>document.getElementById("app");
// Non-null assertionconst value = maybeNull!;
// Const assertionconst config = { url: "/api", method: "GET" } as const;
// Satisfies (TS 4.9+)const palette = { red: [255, 0, 0], green: "#00ff00",} satisfies Record<string, string | number[]>;Common Patterns
Section titled “Common Patterns”// Discriminated unionstype Result<T> = { success: true; data: T } | { success: false; error: string };
function handle<T>(result: Result<T>) { if (result.success) { return result.data; } throw new Error(result.error);}
// Builder pattern with method chainingclass QueryBuilder { select(fields: string[]): this { return this; } where(condition: string): this { return this; } build(): string { return ""; }}
// Branded typestype UserId = string & { readonly brand: unique symbol };function createUserId(id: string): UserId { return id as UserId;}See Also
Section titled “See Also”- TypeScript Lesson Plan — Progressive TypeScript lessons
- Testing — Testing TypeScript code
- Learning a Language — Phases, techniques, anti-patterns