Ts

Creating TypeScript Models for Angular 2

Construct contracts around complex data that your Angular application uses.

Eric Simons Up to date (Jun '17) TypeScript
PRO

As we covered in our "Getting Started with TypeScript" tutorial, the biggest feature that TypeScript brings developers is the ability add explicit types to Javascript variables. For example, if we have a variable called name that should only be a string, we can tell TypeScript to throw an error should name ever be set to anything other than a string (like an integer, object, etc):

let name: string;

This is pretty straightforward for declaring individual variables — but what if we want to create types that represent more complex data structures? In other words, what if we want to create models for what standard objects and/or classes in our application should look like?

For those who have worked with MVC frameworks before, typically you declare types in a model which can then be reused throughout the rest of the application. With TypeScript, frontend applications can now benefit from strongly typed models!

While TypeScript has interfaces that can provide this functionality, the Angular team recommends just using a bare ES6 class with strongly typed instance variables. ES6 classes allow you to (optionally) build out functionality around your models and also doesn't require you to be locked into a TypeScript specific feature. For these reasons, it's advisable to use classes for creating models.

A simple example of this is a User class that defines a name variable that's a string and an age variable that must be a number:

export class User {
  name: string = 'Angular2';
  age: number = 0;
}

Per the Angular Style Guide, models should be stored under a shared/ folder if they will be used in more than one part of your application (which models typically are).

You can view the working source code of this example here:

To recap, to create a model in Angular 2 you just create a class with typed instance variables which can then be imported across the app to ensure complex objects adhere to a certain data spec!