Monthly Archives: May 2021

Using interfaces in Typescript and Angular

One of TypeScript’s core principles is that type-checking focuses on the shape that values have. Basically, as long as an object has the properties required by a function, it’s good to go. It can be a pain in the ass, especially when you come from strictly typed languages.

Introduced in Typescript 2.1, interfaces are your solution to work this issue around. They allow you to define contracts, and to enforce that these contracts are respected. They allow static type checking, and so your IDE can detect errors at compile time, while preserving runtime efficiency since interfaces do not appear in the generated javascript code !

Hence, interfaces solve a common typescript issue when working with objects which have been dynamically casted, and hence may have all properties from the target class, but no the methods. This is a frequent with JSON objects returned by an HTTP call to a REST API and then casted to a different type. Working with interfaces will help you avoid the “method undefined” error.

you define you interface similarly to how you define a class

export interface Book {
  name: string;
  description?: string;
}

Notice the ‘?’ suffix, which indicates that these properties are not mandatory. This will help with initialization of instances of your interface without requiring to initialize all properties :

const myBook: Book = { name: "My new book" };

So, once we know why we must use interfaces, next question is when we should rather use classes. The Mozilla Developper Network gives a quite straightforward answer :

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.