Naming custom types using interfaces

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?

Don't prefix your interface names with I (for example, IService, and IController); this isn't useful in modern languages and hinders readability. If you use good editors, then the fact that your code is using interfaces should be obvious.

Let's see what else we can do using interfaces.

You can also mark some interface properties with readonly, just like with classes.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.182.179