TypeScript Cheatsheet
10xdev.blog/cheatsheets
# 1. Basic Types
// Variable declaration with types
let framework: string = "TypeScript";
let version: number = 4.5;
let isAwesome: boolean = true;

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

// Special types
let anything: any = 4; // Avoid if possible
let unknownType: unknown = "I could be anything";
let nothing: void = undefined; // Used for functions that don't return
let noValue: null = null;
let notAssigned: undefined = undefined;

// Tuples: fixed number of elements with known types
let person: [string, number] = ["Alice", 30];
# 2. Advanced Types
// Union Type: can be one of several types
let id: string | number;
id = "123";
id = 123;

// Type Alias: create a new name for a type
type UserID = string | number;
let userId: UserID = "user-5";

// Intersection Type: combine multiple types
type Draggable = { drag: () => void; };
type Resizable = { resize: () => void; };
type UIWidget = Draggable & Resizable;
let widget: UIWidget = {
  drag: () => console.log("dragging"),
  resize: () => console.log("resizing"),
};

// Literal Types: be specific with values
type Status = "success" | "error" | "pending";
let currentStatus: Status = "pending";
# 3. Functions
// Function with typed parameters and return value
function add(a: number, b: number): number {
  return a + b;
}

// Arrow function syntax
const subtract = (a: number, b: number): number => a - b;

// Optional and Default Parameters
function greet(name: string, greeting?: string): string {
  return `${greeting || "Hello"}, ${name}!`;
}
console.log(greet("World")); // "Hello, World!"
console.log(greet("World", "Hi")); // "Hi, World!"

// Rest Parameters
const sum = (...numbers: number[]): number => {
  return numbers.reduce((acc, num) => acc + num, 0);
};
console.log(sum(1, 2, 3, 4)); // 10
# 4. Interfaces & Classes
// Interface: defines a contract for an object's shape
interface Person {
  readonly id: number; // Read-only property
  name: string;
  age?: number; // Optional property
  greet(): string;
}

// Class implementing an interface
class Employee implements Person {
  readonly id: number;
  name: string;
  department: string;

  constructor(id: number, name: string, department: string) {
    this.id = id;
    this.name = name;
    this.department = department;
  }

  greet(): string {
    return `Hello, my name is ${this.name}.`;
  }
}

const emp = new Employee(1, "Bob", "Engineering");
console.log(emp.greet());
# 5. Generics
// Generic Function
function wrapInArray<T>(item: T): T[] {
  return [item];
}
let stringArray = wrapInArray("hello"); // Type is string[]
let numberArray = wrapInArray(123);   // Type is number[]

// Generic Interface
interface Result<T> {
  data: T | null;
  error: string | null;
}

function fetchUsers(): Result<{ name: string }[]> {
  // Pretend fetch
  return { data: [{ name: "Alice" }], error: null };
}

// Generic Class
class Box<T> {
  private _item: T;
  constructor(item: T) {
    this._item = item;
  }
  getItem(): T {
    return this._item;
  }
}
const stringBox = new Box("A string");
# 6. Enums
// Numeric Enum (defaults to 0, 1, 2...)
enum Direction {
  Up,
  Down,
  Left,
  Right,
}
let move: Direction = Direction.Up; // move is 0

// String Enum
enum HttpStatus {
  OK = "OK",
  NotFound = "NOT_FOUND",
  ServerError = "SERVER_ERROR",
}
let status: HttpStatus = HttpStatus.OK; // status is "OK"
# 7. TypeScript Tooling
# 1. Install TypeScript globally (or as a dev dependency)
npm install -g typescript

# 2. Initialize a TypeScript project (creates tsconfig.json)
tsc --init

# tsconfig.json is highly configurable. Key options:
# "target": "es2016"  // JS version to compile to
# "module": "commonjs" // Module system
# "strict": true       // Enable all strict type-checking options
# "outDir": "./dist"   // Output directory for compiled JS
# "rootDir": "./src"   // Root directory of source TS files

# 3. Compile your TypeScript code
tsc

# 4. Watch for changes and re-compile
tsc --watch
master* 0 0