Skip to content

Classes and interfaces ​

Classes support fields with initializers, constructors, methods, single inheritance with extends, super(...) and super.method(), override, and instanceof. Interfaces are structural, as in TypeScript: a class instance and a plain object literal can both satisfy the same interface, and a call through the interface dispatches to whichever one it holds.

ts
// Classes with inheritance, super calls, overrides and instanceof; an interface implemented by
// a class and satisfied by a plain object literal, called through the interface.
interface Named {
  name: string;
  greet(): string;
}

class Animal implements Named {
  name: string;
  legs: number;
  constructor(name: string, legs: number) {
    this.name = name;
    this.legs = legs;
  }
  greet(): string {
    return `${this.name} has ${this.legs} legs`;
  }
}

class Bird extends Animal {
  canFly: boolean;
  constructor(name: string, canFly: boolean) {
    super(name, 2);
    this.canFly = canFly;
  }
  override greet(): string {
    return super.greet() + (this.canFly ? " and flies" : " and walks");
  }
}

const robot: Named = {
  name: "unit-7",
  greet: (): string => "beep",
};

const all: Named[] = [new Animal("cat", 4), new Bird("penguin", false), robot];
for (const n of all) {
  console.log(n.greet(), n instanceof Bird);
}
text
cat has 4 legs false
penguin has 2 legs and walks true
beep false

How it compiles ​

Every object, class instance or literal, starts with a pointer to an immutable runtime shape that maps field names to slots and method names to functions. Because the program is compiled whole, the compiler knows every shape that can reach a given static type. When they all agree on where a field lives, p.x is a single load; when they do not (the interface above, which is satisfied by two classes and a literal), the site gets an inline cache keyed on the shape. See How it works.

Limits today ​

  • Methods written inside an object literal (greet() { ... }) are rejected with CS1000; use an arrow-function field as above, or a class.
  • Getters and setters, abstract, access modifiers such as private and readonly, and static members are not supported yet (CS1000).
  • Objects cannot gain properties after creation (CS1235). Declare every field up front, optional if needed.

Next: Unions and narrowing.