TypeScript Classes and Modules

Classes, access modifiers, inheritance, modules, and validation boundaries.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Classes
Define a class
class User {
  constructor(public id: number, public name: string) {}
}

# Type instance fields and constructor parameters.

Use access modifiers
class Counter {
  private value = 0;

  increment() {
    this.value += 1;
  }
}

# Control visibility with `public`, `private`, and `protected`.

Readonly class fields
class Config {
  readonly env: string;

  constructor(env: string) {
    this.env = env;
  }
}

# Prevent reassignment after construction.

Extend a class
class Animal {
  move() {
    return "moving";
  }
}

class Bird extends Animal {
  fly() {
    return "flying";
  }
}

# Reuse behavior with inheritance.

Use an abstract class
abstract class Repository<T> {
  abstract findById(id: string): T | undefined;
}

# Require derived classes to implement specific methods.

Use getters and setters
class Temperature {
  private celsius = 0;

  get fahrenheit() {
    return this.celsius * 1.8 + 32;
  }

  set fahrenheit(value: number) {
    this.celsius = (value - 32) / 1.8;
  }
}

# Wrap computed or validated access around fields.

## Modules and Imports
Named export
export function add(a: number, b: number) {
  return a + b;
}

export const APP_NAME = "CheatSheet";

# Export multiple values from a module.

Default export
export default function formatCurrency(value: number) {
  return `$${value.toFixed(2)}`;
}

# Export one primary value from a module.

Type-only import
import type { User } from "./types";

# Import a type without generating runtime usage.

Re-export from another module
export { add, subtract } from "./math";
export type { MathOptions } from "./types";

# Create barrel files or focused module facades.

Dynamic import
const module = await import("./heavy-module");

# Load a module asynchronously at runtime.

## Errors and Validation Boundaries
Parse JSON into `unknown` first
const raw: unknown = JSON.parse(payload);

# Treat external JSON as unsafe until validated.

Narrow caught errors
try {
  riskyWork();
} catch (error: unknown) {
  if (error instanceof Error) {
    console.error(error.message);
  }
}

# Handle `unknown` errors in catch blocks safely.

Recommended next

No recommendations yet.