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

Get TypeScript Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.