
It’s pretty normal having issues when creating your Typescript interfaces, from having doubts as to when to create a class or the correct structure to use. Your simple models can get bigger and bigger without you even knowing it ! So that’s why this guide has been created, to help you understand the basics of how to create and manage your Typescript interfaces.
The question developers are too afraid to ask, because of shyness or whatever other reason…when do you create a class or an interface ?
First, let’s talk about each one of them.
Think of a toy factory that’s creating the new model of action figures of “ Gentleman Programming ‘’, representing a guy with a moustache whose superpower is to develop applications and teach about them.
Each toy has to be exactly the same, with the same properties and functionalities. If one of them has a moustache that when you touch it, it starts to teach a programming concept ( Toy makers you are free to give me a call ) every single other one is going to have a moustache with the same functionality. And that’s a Class ! It’s a structure that can be re-used to create a certain entity, with their properties and logic, without having to write the same piece of code over and over.
“each toy has to be exactly the same, with the same properties and functionalities”
class GentlemanProgrammerToy {
private moustachePhrase: string;
constructor(moustachePhrase: string) {
this.moustachePhrase = moustachePhrase;
}
moustachePressed() {
alert(this.moustachePhrase);
}
}
Every time you use “GentlemanProgramerToy” to create a new object, it will have a “moustachePhrase” and a method “moustachePressed” with the defined functionality.
Now comes the difficult part, what is an interface ? Think of an interface as a contract, which describes a certain number of specifics that must be respected. For example when you make a work contract, it specifies the amount of money and vacation days you will receive.
That’s exactly what an interface is ! You create a model of what to expect of an object, for example if you want to describe what a person should be, you know that it should have a name, last name, age, etc.
interface Person {
name: string;
lastName: string;
age: number;
}
But that’s not it ! You can even define what this person can do:
interface Person {
name: string;
lastName: string;
age: number;
communicate: () => void;
breath: () => void;
}
Now every-time you want an object to be exactly as a Person, you can use the interface to check that the object has everything it needs.