Skip to main content

Course TypeScript

TypeScript Cheatsheet

A quick, printable reference with essential modern TypeScript syntax: annotations, interfaces, unions, narrowing, generics, classes, utility types, and type guards. Print to PDF with Ctrl/Cmd + P.

PDF / Print

Save or print this cheatsheet as PDF

Print-ready layout: open in one click and save as PDF from your browser, no account or email required.

0. Core TypeScript Invariants & Pitfalls to Avoid

Keep these five static-typing invariants in mind before shipping TS code.

  1. TypeScript types are completely erased at runtime: they never validate untrusted JSON or user input on their own.
  2. Avoid any: it disables type checking downstream; accept unknown and narrow explicitly before use.
  3. Type assertions (x as Foo) only silence the compiler — they do not convert or check values at runtime.
  4. Use as const to freeze literal values so array items or properties stay narrowed instead of widening to string.
  5. Always keep strict: true enabled (and consider noUncheckedIndexedAccess) to catch null, undefined, and sparse lookups.

1. Annotations & Primitive Types

  • Explicit annotation

    const username: string = "Alice";
    const score: number = 100;
    const isActive: boolean = true;

    Add a colon (:) followed by the type after the variable name.

    Pitfall: Always use lowercase primitive types (string, number, boolean) rather than wrapper objects (String, Number, Boolean).

  • Type inference

    const inferredName = "Bob"; // Inferred as "Bob" (literal)
    let inferredNum = 42;       // Inferred as number

    TypeScript automatically infers the type from the initial value.

    Pitfall: Writing let x; without an annotation or initializer falls back to implicit any under loose configs.

2. Arrays & Tuples

  • Arrays (homogeneous)

    const numbers: number[] = [1, 2, 3];
    const strings: Array<string> = ["a", "b", "c"];

    Two equivalent syntaxes to define homogeneous collections.

    Pitfall: Annotate empty arrays explicitly (const ids: string[] = []) so TypeScript does not infer any[] or never[].

  • Tuples (fixed size)

    const response: [number, string] = [200, "OK"];
    const point: [number, number, number] = [10, 20, 30];

    Fixed-length arrays where every index has a specific type.

    Pitfall: Without a tuple annotation, [200, "OK"] widens to (number | string)[] instead of a two-slot tuple.

3. Type Aliases & Interfaces

  • Interfaces

    interface User {
      id: number;
      username: string;
      email?: string; // Optional property
    }

    Ideal for modeling object shapes designed to be extended via extends.

    Pitfall: Two interfaces sharing a name in the same scope merge automatically (declaration merging); use type to forbid redeclaration.

  • Type Aliases

    type Point2D = {
      x: number;
      y: number;
    };
    
    type ID = string | number; // Union

    Name any type expression including unions, tuples, primitives, and intersections.

    Pitfall: Optional properties (email?: string) permit omitting the key, whereas email: string | undefined requires the property key.

4. Unions & Narrowing

  • Union Types

    let id: string | number;
    id = "ABC"; // OK
    id = 123;   // OK

    Allows a variable or parameter to hold multiple alternative types.

    Pitfall: You can only call members common to every union branch until you narrow the value.

  • Type Narrowing

    function printId(id: string | number) {
      if (typeof id === "string") {
        console.log(id.toUpperCase()); // id is string
      } else {
        console.log(id.toFixed());     // id is number
      }
    }

    Control-flow checks isolate the exact runtime branch for the type checker.

    Pitfall: typeof x === "object" matches objects, null, and arrays alike: guard with x !== null and Array.isArray(x).

5. Typed Functions

  • Parameters & return annotations

    function greet(name: string, prefix?: string): string {
      return prefix ? `Hello, ${prefix} ${name}` : `Hello, ${name}`;
    }

    Use (?) to mark an optional parameter.

    Pitfall: Required parameters cannot follow optional parameters; supply a default parameter value instead.

  • Function Type (Signature)

    type MathOp = (a: number, b: number) => number;
    const add: MathOp = (x, y) => x + y;

    Extracts a reusable function signature type.

    Pitfall: Callbacks returning void intentionally accept functions with non-void return values so side-effect callbacks compose easily.

6. Generics

  • Generic Function

    function identity<T>(arg: T): T {
      return arg;
    }
    
    const val = identity<number>(42);

    Preserves full type safety between input parameters and return values.

    Pitfall: Inside .tsx files, <T> parses as JSX unless written as <T,> (trailing comma) or <T extends unknown>.

  • Generic Interface

    interface Box<T> {
      content: T;
    }
    
    const stringBox: Box<string> = { content: "Book" };

    Parameterizes container structures and API response envelopes.

    Pitfall: Constrain type parameters with <T extends { id: string }> rather than escaping to any when accessing properties.

7. Classes & Modifiers

  • Parameter properties

    class User {
      constructor(public username: string, private role: string) {}
    }

    Concise syntax: declares and assigns instance fields directly from constructor parameters.

    Pitfall: TypeScript private only restricts access at compile time: use JS #role for true runtime encapsulation.

  • Abstract Classes

    abstract class Shape {
      abstract getArea(): number;
    }
    class Circle extends Shape {
      constructor(public radius: number) { super(); }
      getArea() { return Math.PI * this.radius ** 2; }
    }

    Cannot be instantiated directly; act as checked blueprints for subclasses.

    Pitfall: Forgetting super() inside a subclass constructor throws a runtime ReferenceError.

8. Utility Types

  • Partial & Readonly

    interface Task { id: number; title: string; }
    type PartialTask = Partial<Task>;   // Makes all fields optional
    type ReadonlyTask = Readonly<Task>; // Prevents property mutations

    Built-in type transformations for optional patches and immutability.

    Pitfall: Partial<T> and Readonly<T> are shallow: nested objects remain required or mutable unless wrapped recursively.

  • Pick & Omit

    interface User { id: number; name: string; email: string; }
    type UserInfo = Pick<User, "name" | "email">; // Extracts fields
    type NewUser = Omit<User, "id">;             // Excludes fields

    Derive safe request/response DTOs by selecting or excluding keys.

    Pitfall: Omit does not verify that excluded key names actually exist on T, so typos fail silently.

9. Advanced Types & Guards

  • Custom Type Guards

    function isString(val: unknown): val is string {
      return typeof val === "string";
    }

    Use the x is Type predicate to propagate narrowing to the caller scope.

    Pitfall: TypeScript trusts your runtime boolean logic: a buggy type guard introduces unsound types everywhere it is called.

  • Literal Types & Const

    type Direction = "up" | "down";
    const config = {
      host: "localhost",
      port: 8080
    } as const; // Makes the entire object deeply readonly

    Literal unions plus as const lock properties down to exact values.

    Pitfall: Adding an explicit ": Config" type annotation erases literal types; validate structure with "satisfies Config" instead.

  • Template Literal Types

    type Status = "success" | "error";
    type Action = "click" | "hover";
    type Event = `${Status}-${Action}`;

    Synthesizes typed string combinations from literal unions.

    Pitfall: Interpolating several large unions multiplies into huge union types that can slow down editor type checking.

10. Async / Await, Promise<T> & Concurrency

  • Async Functions & Awaited<T>

    async function fetchProfile(id: number): Promise<{ id: number; name: string }> {
      return { id, name: 'Ada' };
    }
    type Profile = Awaited<ReturnType<typeof fetchProfile>>;

    Every async function always returns Promise<T>; Awaited<T> unwraps the resolved inner type.

    Pitfall: Forgetting await leaves a truthy Promise: if (fetchProfile(1)) silently evaluates to true at runtime!

  • Promise.all vs Promise.allSettled

    const [users, stats] = await Promise.all([loadUsers(), loadStats()]);
    const settled = await Promise.allSettled([taskA(), taskB()]);
    for (const item of settled) {
      if (item.status === 'fulfilled') console.log(item.value);
    }

    Promise.all preserves heterogeneous tuple types but rejects eagerly; allSettled captures every outcome cleanly.

    Pitfall: Always narrow item.status === "fulfilled" before reading item.value on PromiseSettledResult.

11. Error Handling with unknown & Result<T, E>

  • Safe Catch with unknown

    try {
      runRiskyStep();
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error(msg);
    }

    Under strict mode (useUnknownInCatchVariables), err defaults to unknown and forces narrowing before reading .message.

    Pitfall: JavaScript allows throwing arbitrary values such as strings: caught values are never guaranteed to be Error instances.

  • Result<T, E> Pattern & assertNever

    type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
    function assertNever(x: never): never {
      throw new Error('Unhandled case: ' + String(x));
    }

    Encodes expected failures in return types and enforces exhaustive handling via never.

    Pitfall: Never silence default branches with "as any": assertNever makes every missing case fail at compile time.

12. Modern Strict Patterns (satisfies, Branded, tsconfig)

  • satisfies Operator & Branded Types

    const routes = {
      home: '/',
      api: '/v1',
    } as const satisfies Record<string, string>;
    type UserId = string & { readonly __brand: 'UserId' };

    satisfies verifies structural contracts without widening literal types; branded types stop ID mix-ups.

    Pitfall: Avoid blind "as SpecificType" casts on network JSON: validate unknown payloads at runtime boundaries.

  • Key Strict Flags in tsconfig.json

    {
      "compilerOptions": {
        "strict": true,
        "noUncheckedIndexedAccess": true,
        "exactOptionalPropertyTypes": true
      }
    }

    noUncheckedIndexedAccess types arr[i] and record[k] as T | undefined to prevent silent undefined crashes.

    Pitfall: Disabling strictNullChecks quietly lets null and undefined flow into every variable.