Interfaces as contracts

You can ensure that a class adheres to a particular contract using interfaces. I use the term contract in the sense that all the properties and methods defined in the interface must be implemented in the class.

Let's assume that we have the following Note interface:

interface Note {  wordCount: number}

To implement the interface using a class, we add the implements keyword after the class name followed by the interface we are implementing:

class NoteTaker implements Note {  // Implement wordCount from  // Note interface  wordCount: number;  constructor(count: number) {    this.wordCount = count  }}

Interfaces do not only define the signatures for properties but they also accept function types as methods:

interface Note { wordCount: ...

Get TypeScript 2.x for Angular Developers now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.