TypeScript Cheatsheet

Quick reference for TypeScript syntax — types, interfaces, generics, utility types, and more.

Primitive Types

let name: string = "Alice";
let age: number = 30;
let active: boolean = true;
let nothing: null = null;
let undef: undefined = undefined;
let anything: any = "whatever";
let val: unknown = getData(); // safer than any

Arrays & Tuples

// Arrays
let nums: number[] = [1, 2, 3];
let strs: Array<string> = ["a", "b"];

// Tuples — fixed-length, typed positions
let pair: [string, number] = ["Alice", 30];
let coords: [number, number, number] = [0, 0, 0];

Interfaces

interface User {
  id: number;
  name: string;
  email?: string;       // optional
  readonly createdAt: Date; // read-only
}

// Extending interfaces
interface Admin extends User {
  role: "admin" | "superadmin";
}

// Index signatures
interface StringMap {
  [key: string]: string;
}

Type Aliases

type ID = string | number;
type Status = "active" | "inactive" | "pending";
type Point = { x: number; y: number };

// Function type
type Handler = (event: MouseEvent) => void;

// Intersection types
type AdminUser = User & { role: string };

Functions

// Parameter and return types
function greet(name: string): string {
  return `Hello, ${name}`;
}

// Optional and default parameters
function log(msg: string, level?: string, prefix = "LOG") {}

// Rest parameters
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}

// Arrow functions
const double = (n: number): number => n * 2;

Generics

// Generic function
function identity<T>(val: T): T {
  return val;
}

// Generic interface
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Multiple type parameters
function merge<T, U>(a: T, b: U): T & U {
  return { ...a, ...b } as T & U;
}

Utility Types

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

Partial<User>       // all fields optional
Required<User>      // all fields required
Readonly<User>      // all fields read-only
Pick<User, "id" | "name">   // keep only id and name
Omit<User, "email">         // remove email
Record<string, User>        // { [key: string]: User }
Exclude<"a" | "b" | "c", "a">  // "b" | "c"
Extract<"a" | "b", "a" | "d">  // "a"
NonNullable<string | null>      // string
ReturnType<typeof myFn>         // return type of function
Parameters<typeof myFn>         // parameter types tuple

Enums

// Numeric enum
enum Direction { Up, Down, Left, Right }
const dir: Direction = Direction.Up; // 0

// String enum
enum Status {
  Active = "ACTIVE",
  Inactive = "INACTIVE",
}

// Const enum (inlined at compile time)
const enum Size { Small = 1, Medium = 2, Large = 3 }

Type Guards

// typeof
function print(val: string | number) {
  if (typeof val === "string") {
    console.log(val.toUpperCase());
  }
}

// instanceof
function handle(err: Error | string) {
  if (err instanceof Error) {
    console.log(err.message);
  }
}

// Custom type guard
function isUser(obj: unknown): obj is User {
  return typeof obj === "object" && obj !== null && "id" in obj;
}

Mapped & Conditional Types

// Mapped type
type Optional<T> = { [K in keyof T]?: T[K] };

// Conditional type
type IsString<T> = T extends string ? true : false;

// Infer
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;

// Template literal types
type EventName = `on${Capitalize<string>}`;

Classes

class Animal {
  readonly name: string;
  #sound: string; // private field (ES2022)

  constructor(name: string, sound: string) {
    this.name = name;
    this.#sound = sound;
  }

  speak(): string {
    return `${this.name} says ${this.#sound}`;
  }
}

// Abstract class
abstract class Shape {
  abstract area(): number;
  describe() { return `Area: ${this.area()}`; }
}

// Implementing interfaces
class Dog extends Animal implements Serializable {
  serialize() { return JSON.stringify(this); }
}

Have JavaScript code to convert to TypeScript?

Use the JS to TS Converter →