Ts

Creating TypeScript Models for Angular

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 for services or declarables (components, directives, and pipes) and Interfaces for data models.

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

export interface User {
  name: string = 'Angular';
  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 you just create an Interface with typed instance variables which can then be imported across the app to ensure complex objects adhere to a certain data spec!

 

I finished! On to the next tutorial