Classes

View saved

Create a typed class

Property types live on the class body. The constructor initializes them.

class Counter {
  count: number;

  constructor(start = 0) {
    this.count = start;
  }

  increment(): void {
    this.count += 1;
  }
}

const c = new Counter();
c.increment();
console.log(c.count);

Use public and private

private hides a field from outside code. Parameter properties shorten constructors.

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

  label(): string {
    return `${this.name} (#${this.id})`;
  }
}

console.log(new User(1, "Ada").label());

Implement an interface

Classes can promise to match an interface shape.

interface Greeter {
  greet(): string;
}

class Friendly implements Greeter {
  greet(): string {
    return "Hello!";
  }
}

Class tips for beginners

  • Prefer plain functions and objects until a class earns its keep
  • Mark fields readonly when they should not change
  • Remember types erase: privacy is a compile-time check unless you use newer JS private fields
  • Inheritance works, but composition is often simpler

Comments

One comment per signed-in account. Comments are saved with this page’s URL.