DM
Technical reference

TypeScript Cheatsheet

Typed superset of JavaScript

Getting Started

Basic Types

TypeScript adds static types on top of JavaScript.

let age: number = 18;
let name: string = "John";
let isActive: boolean = true;

Arrays & Tuples

let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["age", 18];

Any & Unknown

`unknown` is safer than `any` — it forces a type check before use.

let a: any = 4;
let b: unknown = "hello";

Interfaces & Types

Interface

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

Type Alias

type Point = { x: number; y: number };

Union Types

type Status = "loading" | "success" | "error";

Extending

interface Admin extends User {
  role: "admin";
}

Functions

Typed Function

function add(x: number, y: number): number {
  return x + y;
}

Optional & Default Params

function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}`;
}

Arrow Function Typing

const multiply = (a: number, b: number): number => a * b;

Classes

Basic Class

class Animal {
  constructor(public name: string) {}
  speak(): void {
    console.log(`${this.name} makes a noise.`);
  }
}

Access Modifiers

class Account {
  private balance: number = 0;
  protected id: string = "acc_1";
  public owner: string = "Luis";
}

Implementing an Interface

class Employee implements User {
  constructor(public id: number, public name: string) {}
}

Generics

Generic Function

function identity<T>(arg: T): T {
  return arg;
}

identity<string>("hello");

Generic Interface

interface ApiResponse<T> {
  data: T;
  error?: string;
}

Utility Types

Partial

Makes all properties optional.

type PartialUser = Partial<User>;

Pick & Omit

type NameOnly = Pick<User, "name">;
type NoEmail = Omit<User, "email">;

Record

type Roles = Record<string, boolean>;

Type Narrowing

typeof Guard

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

instanceof Guard

if (error instanceof Error) {
  console.log(error.message);
}