Search⌘ K

Classes and Type Annotations

Explore how TypeScript extends ES6 class syntax to enforce type safety by explicitly declaring attributes and methods. Learn to use interfaces for defining object shapes and how modifiers like private and readonly manage class properties effectively.

TypeScript Classes

TypeScript takes full advantage of the class features added to JavaScript in ES6.

There are many references for ES6 classes and we can find the basic syntax here.

The goal of the TypeScript extensions to class syntax is to allow the TypeScript compiler to treat object attribute references and method calls the way that functions and assignments are treated. We want to be able to tell from the class of the instance what attributes exist and the expected type of those attributes.

In TypeScript, any method defined in a class is available to instances of the class. We can annotate arguments and return the values of a method just as we would for functions.

The first real change in TypeScript classes compared to JavaScript is the need to explicitly list attributes of the class that would only be created when assigned in plain JavaScript. In TypeScript, if we are going to refer to an attribute like this.color = "red", the existence of the color attribute ...