Book Image

TypeScript Essentials

By : Christopher Nance
Book Image

TypeScript Essentials

By: Christopher Nance

Overview of this book

Table of Contents (15 chapters)

Interfaces


Let's revisit our discussion of interfaces for a moment and look at how they interact with classes. In the next example, we will enforce the IPoint interface upon the Point class. Classes can optionally inherit type information from interfaces using the implements keyword. The class will then be required to implement all of the interface members; otherwise, compile errors will occur:

interface IPoint {
    x: number;
    y: number;
}
class Point implements IPoint {
    constructor(public x: number, public y = 0) {
    }
}

As we discussed earlier, interfaces are a purely compile time construct. The JavaScript that is output from this example is completely identical to the JavaScript we just saw. I snuck in a shorthand method of defining instance variables on classes too. Decorating the constructor's parameters with the public or private keywords tells TypeScript to treat these objects as part of the type and not just initialization parameters.

Classes are not limited to implementing...