Book Image

TypeScript Essentials

By : Christopher Nance
Book Image

TypeScript Essentials

By: Christopher Nance

Overview of this book

Table of Contents (15 chapters)

Classes


In the next version of JavaScript, ECMAScript 6, a standard has been proposed for the definition of classes. TypeScript brings this concept to the current versions of JavaScript. Classes consist of a variety of different properties and members. These members can be either public or private and static or instance members.

Definitions

Creating classes in TypeScript is essentially the same as creating interfaces. Let's create a very simple Point class that keeps track of an x and a y position for us:

class Point {
    public x: number;
    public y: number;
    constructor(x: number, y = 0) {
        this.x = x;
        this.y = y;
    }
}

As you can see, defining a class is very simple. Use the keyword class and then provide a name for the new type. Then you create a constructor for the object with any parameters you wish to provide upon creation. Our Point class requires two values that represent a location on a plane.

Tip

The constructor is completely optional. If a constructor implementation...