Class (TypeScript)

A TypeScript class is a JavaScript class with added type features — typed fields, typed methods, access modifiers, and the ability to implement interfaces. It is a blueprint for creating typed objects.

TypeScript

TypeScript classes build on the JavaScript `class` syntax and add type annotations on fields and methods so the compiler can check them. You declare a field's type, and the constructor must initialize it.

A class can `implements` an interface to guarantee it provides the required shape, and it can use access modifiers like `private` and `public` to control what's visible from outside.

Syntax

class Name {
  field: type;
  constructor() { ... }
}

Examples

TypeScript

class Dog {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  speak(): string {
    return this.name + " says woof";
  }
}

console.log(new Dog("Rex").speak());

Output:

Rex says woof

Learn it in a lesson

See also

Back to the Dictionary