Angular Tutorial for Beginners - Part Four - Interfaces

This is part 4 of the Angular Tutorial for Beginners series.
  • Part 1 of this series discussed how to get started with Angular.
  • Part 2 discussed the basic tenants of Angular Modules, Components, and Directives.
  • Part 3 discussed data binding.
  • Part 4 here builds upon the demo used in the earlier parts to explain the concept of interface. Hence it is strongly advised that you go through them before proceeding.
Interfaces in TypeScript provide type checking. Here, we have defined an array of any as below. But this does not provide any type of checking.
Angular Interfaces
For type checking we will create an interface of employee as below.
We will create typescript file employee.ts and export an interface as below.
Angular Interfaces
  1. export interface IEmployee{  
  2.     employeeId : number;  
  3.     employeeName : string;  
  4.     projectId : number  
  5. }  
Let’s import the employee.ts in employee.component.ts.
Angular Interfaces
Now we replace the array of any with an array of IEmployee in employee.component.ts as below.
Angular Interfaces
Using an interface like IEmployee will provide me with the type checking. If I write ’employeeNames’ instead of ’employeeName’, I will be notified immediately as below. So, this helps in compile-time checking and helps me to catch errors earlier on.
Angular Interfaces
So, what if we use a class instead of an interface for type checking? There is no concept of interfaces in JavaScript. Hence when interfaces are transpiled, there is no code generated. But if we use classes, Javascript code is generated. Using interface, you can avoid this extra javascript code. If you only need to perform type checking, then using interfaces instead of classes is a good option. It's good to know more about Typescript classes & interfaces.
In the next part of the Angular tutorial for Beginners series, we will learn how to use services in Angular.
This article was originally published on my website.

Similar Articles