TypeScript interfaces allow us to define contracts and also to give names to specific types/shapes.
When you need to use a custom type somewhere in your code, you should always consider creating an interface and/or a class for it. We'll soon see what to take into consideration in order to decide whether a class or interface makes more sense.
For now, let's concentrate on the number of times that a given custom type will need to be used. If you only need it in one place, then maybe a custom type is fine. If, on the other hand the custom type is going to be used at multiple locations, then it probably makes more sense to create an interface or a class for it.
Using an interface or class rather than a custom type means that you define the first-level concept for your application, which can tremendously improve the readability of your code.
Let's revisit our previous example:
interface Person {
firstName: string,
lastName: string,
age: number
}
function sayHelloTo(bar: Person): void {
console.log(`Hello ${bar.firstName}.. or should I call you Mr
${bar.lastName}?`);
}
let persjohnDoeon: Person = {
firstName: "John",
lastName: "Doe",
age: 42
};
sayHelloTo(johnDoe);
Isn't it clearer when using interfaces, as we did previously?
Let's see what else we can do using interfaces.