...

/

Classes and Type Annotations

Classes and Type Annotations

Let's learn about classes and type annotations in this lesson.

We'll cover the following...

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

There are a lot of references for ES6 classes; http://es6-features.org has the basic syntax.

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 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. You can annotate arguments and return values of a method just as you 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, in plain JavaScript, only be created when assigned. In TypeScript, if you are going to refer to an attribute like this.color = "red", the existence of the color attribute needs to have already been declared.

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

export default class
...