Classes & Modules

TypeScript classes, access modifiers, modules, and generics.

Classes

class Person {
  // Access modifiers: public (default), private, protected
  constructor(
    public name: string,
    private birthYear: number,
    readonly id: number
  ) {}

  get age(): number {
    return new Date().getFullYear() - this.birthYear;
  }

  toString(): string {
    return `Person(${this.name})`;
  }
}

const p = new Person("Ada", 1985, 1);
console.log(p.name);  // "Ada"
// p.birthYear; // Error: private

Inheritance

class Employee extends Person {
  constructor(
    name: string,
    birthYear: number,
    id: number,
    public company: string
  ) {
    super(name, birthYear, id);
  }
}

Abstract classes

abstract class Shape {
  abstract area(): number;
}

class Circle extends Shape {
  constructor(public radius: number) { super(); }
  area(): number { return Math.PI * this.radius ** 2; }
}

Interfaces for Classes

interface Loggable {
  log(): void;
}

class Logger implements Loggable {
  log(): void {
    console.log("logged");
  }
}

Modules

// utils.ts
export function add(a: number, b: number): number {
  return a + b;
}

export const PI = 3.14159;

export default class Calculator { ... }
// app.ts
import Calculator, { add, PI } from "./utils";
import * as utils from "./utils";

Generics in Classes

class Store<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  getAll(): T[] {
    return [...this.items];
  }
}

const store = new Store<string>();
store.add("hello");

Next: Back to TypeScript overview