Typescript Interfaces – Part 1 Introduction
Introduction Into Typescript Interfaces
This tutorial is written more for those who are new to a type safe environment. The idea of types can be somewhat confusing for someone who is coming from es5 / es6 or any non strictly typed language. You can find out more about what I mean regarding types in one of my other articles (coming soon). This will be a short series of articles.
So.. an interface, what is it, how do I use it and more to the point, why would I use it. Well, imagine you have an object, and you’re adding properties to this object all willy nilly then passing it around.
Every time you go to access a property, you need to look up to see if that was the name, or the that was the property you actually wanted in the first place. What if there was a way to write a tiny dictionary, a little booklet of information saying what this object is and what properties and their types are in there. Welcome, to the world of interfacing.
Little side note, yes some IDE’s will remind you what properties you have added to your object, but if you are sharing your project with other developers, and you cannot guarantee that they will also use the same IDE, they will loose this benefit.
Lets examine the following example:
declare interface iPerson {
name: string;
}
let john: iPerson = {
name: 'John'
}
So what did we do, And who is John anyway?!
Okay, so the example is a basic one, but enough to get the point across. We declared that an interface iPerson
has to contain the property name, and that name has to be a type string. Next we go ahead and make a new variable called john, and declare it’s type of iPerson. Now if we passed an empty object, it would throw an error. That’s because without being told otherwise, typescript assumes all properties must be present.
In order to overcome this, and have optional properties, you can make it optional by simply adding a question mark.
declare interface iPerson {
name: string;
age?: number;
}
let john: iPerson = {
name: 'John'
}
The above now doesn’t throw an error as name is required, but age isn’t. However the age property still exists on anything with type iPerson, but it may be undefined as it’s optional.
Continue on to Part 2 to get into nested interfaces.[/vc_column_text][/vc_column][/vc_row]