Classes and Type Annotations

Let’s have a look at how we can declare classes and define interfaces in TypeScript.

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 needs to have already been declared.

GenericToggle Class

Again, we’ve already seen this at the beginning of our GenericToggle class:

Get hands-on with 1400+ tech skills courses.