TypeScript Interfaces: A Practical Guide with Code Examples & Usecase

Salman Asu - Sep 3 - - Dev Community

To define the structure or shape of an object and specify the properties and methods that an object has or should have. Interface is built-in feature of typescript.

use interface if it possible instead of types.


simple example

interface Person {
    name: string;
    age: number;
    sex: "male" | "female";
}

const personOne: Person = {
    name: "sallbro",
    age: 22,
    sex: "male",
}

console.log(personOne.name); // sallbro
// 👇 Property 'hobbies' does not exist on type 'Person'
console.log(personOne.hobbies); // undefined
Enter fullscreen mode Exit fullscreen mode

As you can see in the above code block, we access a property that is defined in the interface with no issues by running console.log(personOne.name).

We also can see an example of us trying to access a property that doesn’t exist in the interface by running console.log(personOne.hobbies), therefore throwing a type error.

when should we use & benefit of interface

Now that we understand a bit more about interfaces, what they look like, and how to use them, let’s take a closer look at their benefits to us.

Type checking
The first benefit of interfaces is the most obvious one: they highlight any possible type errors and issues in our code to prevent us from accessing any properties that might not exist. This, in turn, helps us reduce runtime errors and prevent bugs from being created.

Contract definition
Another benefit of interfaces is that they define and create clear contracts for the functions and code that consume them. They prevent us from consuming methods and properties that don’t exist and help ensure we stay within the established structure defined for the object that the interface is describing.

. .
Terabox Video Player