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

Class fields, constructors, access modifiers, and inheritance.

Define a class

Type instance fields and constructor parameters.

typescriptANYtypescriptclasses
typescript
class User {
  constructor(public id: number, public name: string) {}
}
Notes

Parameter properties create and assign fields directly from constructor parameters.

Use access modifiers

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

typescriptANYtypescriptclassesaccess-modifiers
typescript
class Counter {
  private value = 0;

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

Access modifiers are checked at compile time and influence editor API surface.

Readonly class fields

Prevent reassignment after construction.

typescriptANYtypescriptclassesreadonly
typescript
class Config {
  readonly env: string;

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

Readonly is useful for IDs, config values, and immutable domain objects.

Extend a class

Reuse behavior with inheritance.

typescriptANYtypescriptclassesinheritance
typescript
class Animal {
  move() {
    return "moving";
  }
}

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

Inheritance works well for simple hierarchies, though composition is often easier to maintain.

Use an abstract class

Require derived classes to implement specific methods.

typescriptANYtypescriptclassesabstract
typescript
abstract class Repository<T> {
  abstract findById(id: string): T | undefined;
}
Notes

Abstract classes are useful when shared implementation and a contract both matter.

Use getters and setters

Wrap computed or validated access around fields.

typescriptANYtypescriptclassesgetters-setters
typescript
class Temperature {
  private celsius = 0;

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

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

Getters and setters let APIs expose properties while keeping internal conversions hidden.

Modules and Imports

ES modules, type-only imports, and export patterns.

Named export

Export multiple values from a module.

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

export const APP_NAME = "CheatSheet";
Notes

Named exports scale well when a module exposes several helpers.

Default export

Export one primary value from a module.

typescriptANYtypescriptmodulesexportsdefault-export
typescript
export default function formatCurrency(value: number) {
  return `$${value.toFixed(2)}`;
}
Notes

Default exports are common, but many teams prefer named exports for consistency.

Type-only import

Import a type without generating runtime usage.

typescriptANYtypescriptmodulesimport-type
typescript
import type { User } from "./types";
Notes

Type-only imports help avoid accidental runtime dependencies and can improve clarity.

Re-export from another module

Create barrel files or focused module facades.

typescriptANYtypescriptmodulesre-export
typescript
export { add, subtract } from "./math";
export type { MathOptions } from "./types";
Notes

Barrel files can simplify imports, but use them thoughtfully to avoid confusing dependency graphs.

Dynamic import

Load a module asynchronously at runtime.

typescriptANYtypescriptmodulesdynamic-import
typescript
const module = await import("./heavy-module");
Notes

Dynamic imports are useful for code splitting and conditional loading.

Errors and Validation Boundaries

Handle unknown inputs safely and validate external data.

Parse JSON into `unknown` first

Treat external JSON as unsafe until validated.

typescriptANYtypescriptunknownjsonvalidation
typescript
const raw: unknown = JSON.parse(payload);
Notes

Using `unknown` forces validation before use and is safer than blindly asserting types.

Narrow caught errors

Handle `unknown` errors in catch blocks safely.

typescriptANYtypescripterrorsunknown
typescript
try {
  riskyWork();
} catch (error: unknown) {
  if (error instanceof Error) {
    console.error(error.message);
  }
}
Notes

Catches should treat errors as unknown at boundaries and narrow deliberately.

Recommended next

No recommendations yet.