Skip to content

Instantly share code, notes, and snippets.

@razhangwei
Created February 8, 2025 23:03
Show Gist options
  • Save razhangwei/96828a46f1c3989413fb04c49d06ad3e to your computer and use it in GitHub Desktop.
Save razhangwei/96828a46f1c3989413fb04c49d06ad3e to your computer and use it in GitHub Desktop.
TypeScript Cheatsheet

TS (TypeScript) is a strongly-typed superset of JavaScript developed by Microsoft. It adds optional static typing, modern JavaScript features, and tooling to enhance code quality and maintainability. TypeScript compiles to plain JavaScript and is widely used for large-scale applications.


TypeScript Cheatsheet

1. Basic Types

let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 42]; // Fixed-type array
enum Color { Red = "RED", Green = "GREEN" }; // Enumerations
let notSure: any = "could be anything"; // Opt-out of type-checking
let nothing: void = undefined; // Common for function returns

2. Interfaces

Define object shapes:

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

const user: User = { id: 1, name: "Alice" };

3. Functions

Type annotations for parameters and return values:

function add(a: number, b: number): number {
  return a + b;
}

// Optional/default parameters
function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}

4. Classes

class Person {
  private age: number; // Access modifiers: public, private, protected

  constructor(public name: string, age: number) {
    this.age = age;
  }

  // Method
  describe(): string {
    return `${this.name} is ${this.age} years old.`;
  }
}

// Inheritance
class Employee extends Person {
  constructor(name: string, age: number, public role: string) {
    super(name, age);
  }
}

5. Generics

Reusable code with type variables:

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

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

const response: ApiResponse<User> = { data: user, status: 200 };

6. Unions & Intersections

type StringOrNumber = string | number; // Union
type Combined = User & { permissions: string[] }; // Intersection

7. Type Guards

Check types at runtime:

if (typeof value === "string") { /* ... */ }
if (value instanceof User) { /* ... */ }

8. Advanced Types

  • Type Aliases: type Point = { x: number; y: number };
  • Utility Types:
    • Partial<T>: All properties optional.
    • Pick<T, K extends keyof T>: Select subset of properties.
    • Record<K, T>: Map a type to keys.
    • Readonly<T>: Immutable properties.

9. Compilation

Compile TypeScript to JavaScript:

tsc file.ts # Generates file.js

Use a tsconfig.json for project settings:

{
  "compilerOptions": {
    "target": "ES6",
    "strict": true
  }
}

Example: Full Snippet

interface Product {
  id: number;
  name: string;
  price: number;
}

class Cart {
  private items: Product[] = [];

  addItem(item: Product): void {
    this.items.push(item);
  }

  total(): number {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }
}

const cart = new Cart();
cart.addItem({ id: 1, name: "Laptop", price: 999 });
console.log(cart.total()); // 999
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment