Tag Archives: Interfaces

Typescript Interfaces

One of my favourite features of Typescript is the Interfaces feature which provides us with a really easy way of type-checking our custom objects.  You can think of Interfaces as a type of contract that must be fulfilled by your code.

For example, let’s say you have an Ionic component which displays some sort of membership list showing name, age and registered (Y/N).  You could come up with something like this (this is a very simplistic example with hard-coded data):

import { Component } from ‘@angular/core’;

@Component({
selector: ‘page-members’,
templateUrl: ‘members.html’
})

export class MembersPage {

members: any[];

constructor() {
this.members = [
{
name:”Sally Taylor”,
age:21,
registered:true
},
{
name:”Mike Smith”,
age:25,
registered:false
}
]
}

}

This is ok and will work but if you were to change one of those data objects so that, for example, instead of

registered: true

you had

registered: “yes”

your editor won’t complain about the error.  Even though you have supplied an invalid object, the editor does not know that each object in the array should contain a string (name), a number (age) and a boolean (registered).

This is where interfaces help you.

First, we define an interface for our object type (which we will call member)

interface member {
name:string,
age: number,
registered:boolean
}

Then we simply state that the members array must be an array of objects of type member:

members: member[];

that’s all there is to it.  So the component would then look like this>

import { Component } from ‘@angular/core’;

interface member {
name:string,
age: number,
registered:boolean
}

@Component({
selector: ‘page-members’,
templateUrl: ‘members.html’
})

export class MembersPage {

members: member[];

constructor() {
this.members = [
{
name:”Sally Taylor”,
age:21,
registered:true
},
{
name:”Mike Smith”,
age:25,
registered:false
}
]
}

}

Now if you were to change either of the objects so that they did not match the contract of name (string), age (number) and registered(boolean) your editor will produce an error.  This type of type checking can save you a lot of debugging time later on.

Usually, I put my interfaces in a separate file (in a models folder) and import them.  That way you can easily use your interfaces in multiple components.