Classes, Enums and Access Modifiers

Harry · 14 Sep 2026 · 2 views
Advertisement
Advertisement

Classes with typed members

class Account {
  balance: number;

  constructor(initial: number) {
    this.balance = initial;
  }

  deposit(amount: number): void {
    this.balance += amount;
  }
}

const a = new Account(100);
a.deposit(50);

Access modifiers

TypeScript adds public (default), private and protected to control visibility. A shorthand lets the constructor declare and assign fields in one go:

class Person {
  constructor(
    public name: string,
    private ssn: string
  ) {}
}
const p = new Person("Ada", "123");
p.name;    // OK
p.ssn;     // Error: 'ssn' is private

Inheritance and interfaces

interface Shape { area(): number; }

class Circle implements Shape {
  constructor(private r: number) {}
  area(): number { return Math.PI * this.r ** 2; }
}

class Cylinder extends Circle {
  constructor(r: number, private h: number) { super(r); }
}

implements promises a class satisfies an interface; extends inherits from another class and super() calls the parent constructor.

Enums

An enum names a set of related constants:

enum Direction { North, East, South, West }
let d: Direction = Direction.North;

enum Status { Active = "ACTIVE", Banned = "BANNED" }  // string enum

For a simple fixed set, a literal union ("North" | "East" | ...) is often lighter; enums shine when you want named, iterable constants.

Key points

  • Class fields are typed; the constructor can declare and assign them via modifiers.
  • public/private/protected control member visibility.
  • implements enforces an interface; extends inherits a class.
  • Enums name related constants; literal unions are a lighter alternative.
Share this post:

Comments (0)

Please login or register to comment.