Search⌘ K

Classes and Type Annotations

Explore how TypeScript extends JavaScript's ES6 class syntax by enabling explicit declaration of class attributes with type annotations. Learn to define methods with typed parameters and return values. Understand the use of access modifiers including readonly, and the role of interfaces to enforce structured data types in your code. Discover how classes can implement interfaces and how interfaces extend other interfaces to create reusable type contracts.

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 GenericToggle {
...