Interfaces in typescript
Tags: typescript, javascript, beginners, web
Published: 2023-03-31 18:55:28

In TypeScript, interfaces are used to define the shape of an object, including its properties and methods. They serve as a contract that specifies what properties and methods an object should have, without specifying how they should be implemented. In this article, we will explore the use of interfaces in TypeScript with examples.

Defining an Interface

To define an interface in TypeScript, we use the keyword interface, followed by the name of the interface and a pair of curly braces. Inside the curly braces, we specify the properties and methods that should be present in the object that implements this interface. Here is an example:


```
interface Person {
    firstName: string;
    lastName: string;
    age: number;
    sayHello(): void;
}
```

In this example, we have defined an interface called Person that specifies that any object that implements this interface must have firstName, lastName, and age properties that are of type string, string, and number, respectively. Additionally, the object must have a sayHello() method that returns void.

Implementing an Interface

To implement an interface, we create a new object and specify the properties and methods that are required by the interface. Here is an example:


```
class Employee implements Person {
    firstName: string;
    lastName: string;
    age: number;

    constructor(firstName: string, lastName: string, age: number) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    sayHello() {
        console.log("Hello, my name is " + this.firstName + " " + this.lastName);
    }
}

```

```
let employee = new Employee("John", "Doe", 30);
employee.sayHello(); // Output: "Hello, my name is John Doe"
```

In this example, we have created a Person interface, which specifies the properties and methods that should be present in an object that implements this interface. We have also created a class called Employee that implements the Person interface by defining all the required properties and methods.

Using an Interface as a Type

In addition to defining the shape of an object, interfaces can also be used as a type. This allows us to specify that a variable or function parameter should be of a certain type, based on an interface. Here is an example:



```
function printPerson(person: Person) {
    console.log("Name: " + person.firstName + " " + person.lastName);
    console.log("Age: " + person.age);
    person.sayHello();
}
```

```
let employee = new Employee("John", "Doe", 30);
printPerson(employee); // Output: "Name: John Doe", "Age: 30", "Hello, my name is John Doe"
```

In this example, we have defined a printPerson() function that takes an argument of type Person. We have also created an Employee object and passed it as an argument to the printPerson() function. Since the Employee class implements the Person interface, it is also considered to be of type Person, and the function can be called with an instance of Employee.

Interfaces in TypeScript have several real-world applications, and they are used extensively in the development of software systems. Here are some examples of how interfaces are used in real-world applications.

1. API Design

When designing an API, interfaces are used to define the data structures that will be used to exchange data between the client and the server. This allows the client and server to agree on the format of the data, making it easier to communicate and reducing the likelihood of errors. For example, consider the following interface that defines the structure of a User object in a social media application:

```
interface User {
  id: number;
  name: string;
  email: string;
  dateOfBirth: Date;
  gender: 'Male' | 'Female' | 'Other';
}
```

This interface can be used to define the structure of the JSON data that is sent and received by the API.

2. Object-oriented Programming

In object-oriented programming, interfaces are used to define contracts that classes must adhere to. This allows classes to be interchangeable, making it easier to write modular and maintainable code. For example, consider the following interface that defines the contract for a Vehicle class:

```
interface Vehicle {
  startEngine(): void;
  stopEngine(): void;
  accelerate(speed: number): void;
  brake(): void;
}
```

This interface can be implemented by various classes such as Car, Motorcycle, and Truck, each of which would provide their own implementation of the methods.

3. Third-party Libraries

Interfaces are also used by third-party libraries to define the structure of their API. This allows developers to use the library in a consistent and predictable manner, reducing the likelihood of errors. For example, the following interface defines the structure of the Moment.js library, which is used to manipulate dates and times in JavaScript:

```
interface Moment {
  (input?: MomentInput, format?: MomentFormatSpecification, strict?: boolean): Moment;
  format(format: string): string;
  add(amount: MomentInput, unit: MomentUnit): Moment;
  subtract(amount: MomentInput, unit: MomentUnit): Moment;
  isBefore(other: Moment | string | number | Date | (number | string | Date)[]): boolean;
  isAfter(other: Moment | string | number | Date | (number | string | Date)[]): boolean;
  // ...
}
```

This interface allows developers to use the Moment.js library in a consistent and predictable manner, without having to understand the underlying implementation.



Conclusion

Interfaces in TypeScript are a powerful tool for defining the shape of an object, and specifying the properties and methods that should be present in an object that implements this interface. They allow us to write more robust and maintainable code by enforcing a certain level of type safety. By implementing an interface, we can ensure that our classes conform to a certain shape, and by using an interface as a type, we can specify that a variable or function parameter should be of a certain type, based on an interface.