05 objects and classes

TypeScript is structurally typed If two shapes have the same members, they are compatible That surprises people coming from nominal languages

Table of Contents

Interfaces

interface Target {
  host: string;
  port?: number;
}

An interface describes a shape type can describe the same thing Interfaces can be reopened by declaration merging, type aliases cannot

Readonly

interface ReadableTarget {
  readonly host: string;
  port?: number;
  [key: string]: string | number | undefined;
}

readonly stops reassignment after creation It does not make an object deeply immutable For that you still need runtime freezing or a library

Index signatures

The [key: string] line above allows extra keys The value type must cover all declared properties undefined is included because port is optional

Index signatures are useful for dictionaries They are dangerous when they hide typos in property names

Classes

abstract class Scanner {
  constructor(protected readonly name: string) {}
  abstract scan(): string;
  describe(): string {
    return `${this.name} ready`;
  }
}

class NmapScanner extends Scanner {
  scan(): string {
    return `${this.name} scanning`;
  }
}

abstract means you cannot instantiate the base directly protected lets subclasses access the field abstract scan() forces subclasses to implement it

TypeScript adds parameter properties and access modifiers Everything else is regular JavaScript class syntax

Posted