8-TS OOP: Interfaces: Contracts
Tags: javascript, oop, typescript
Published: 2022-11-21 16:43:22

---
title: 8-TS OOP: Interfaces: Contracts
published: true
description: 
series: jstsoop
tags: javascript, oop, typescript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l9qoiujfoqcv60dxrycy.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-25 09:51 +0000
---

## What is an Interface?

An interface is a `contract` that tells other classes what is the structure of the class that implements it.

## Why do we need Interfaces?

Interfaces are used to define the structure of a class so others can work with it without knowing the implementation details but they know what this class contains.

## Interfaces in Typescript

Unfortunately, interfaces are not available in `Javascript` but they are available in `Typescript`.

## How to define an Interface?

To define an interface, we use the `interface` keyword.

Let's see an example:

```ts
interface HumanInterface {
    name: string;
    age: number;
}
```

Here we have an interface called `Human` that has 2 properties, `name` and `age`.

## How to use an Interface?

To use an interface, we use the `implements` keyword.

Let's see an example:

```ts
class Human implements HumanInterface {
    name = 'Hasan';
    age = 33;
}
```

Here we have a class called `Human` that implements the `HumanInterface` interface.

We can also define methods in an interface:

```ts
interface HumanInterface {
    name: string;
    age: number;
    sayHello(): void;
}
```

The method defined in the interface does not have a body, we can define its name, its parameters types and its return type.

Now let's implement the interface in a class:

```ts
class Human implements HumanInterface {
    name = 'Hasan';
    age = 33;
    sayHello() {
        console.log('Hello');
    }
}
```

Let's see another method that has parameters:

```ts
interface HumanInterface {
    name: string;
    age: number;
    sayHello(name: string): void;
}
```

Now let's implement the interface in a class:

```ts
class Human implements HumanInterface {
    name = 'Hasan';
    age = 33;
    sayHello(name: string) {
        console.log(`Hello ${name}`);
    }
}
```

## Interfaces are Contracts

As we mentioned in the beginning, interfaces are contracts that tell other classes what is the structure of the class that implements it.

Let's talk about a real world project example, let's say we have an online store that accepts multiple payment methods, for example `PayPal`, `Stripe`, `Cash`, `Credit Card`, etc.

We want to create the order of the customer but before that we want to perform the payment operation.

So we can create an interface called `PaymentInterface` that has a method called `pay` that accepts the amount to pay and returns a boolean value that indicates if the payment is successful or not.

```ts
interface PaymentInterface {
    pay(amount: number): boolean;
}
```

Now let's create multiple classes that implement this interface:

```ts
class PayPal implements PaymentInterface {
    pay(amount: number) {
        // Do the payment operation
        return true;
    }
}

class Stripe implements PaymentInterface {
    pay(amount: number) {
        // Do the payment operation
        return true;
    }
}

class Cash implements PaymentInterface {
    pay(amount: number) {
        // Do the payment operation
        return true;
    }
}

class CreditCard implements PaymentInterface {
    pay(amount: number) {
        // Do the payment operation
        return true;
    }
}
```

Now we can use these classes in our `Order` class:

```ts
class Order {
    payment: PaymentInterface;
    public isPaid: boolean = false;
    constructor(payment: PaymentInterface) {
        this.payment = payment;
    }

    /**
     * Pay the order
     */
    pay(amount: number) {
        this.isPaid = this.payment.pay(amount);
    }

    /**
     * Create the order
     */
    placeOrder() {
        //
    } 
}

const paymentMethod = new PayPal();

const order = new Order(paymentMethod);

order.pay(100);

if (order.isPaid) {
    order.placeOrder();
}
```

Here we have an `Order` class that has a property called `payment` that is an instance of `PaymentInterface`.

Regardless of the payment method, we can use the `Order` class without knowing the implementation details of the payment method and what is going to happen when we call the `pay` method, we just know that the given payment method has a `pay` method that accepts the amount to pay and returns a boolean value that indicates if the payment is successful or not.

## Interfaces are not Classes

Interfaces are not classes, they are just contracts that tell other classes what is the structure of the class that implements it.

So we can not create an instance of an interface, we can only create an instance of a class that implements an interface.

## Extending Interfaces

We can extend interfaces, let's see an example:

```ts
interface HumanInterface {
    name: string;
    age: number;
    sayHello(): void;
}

interface DeveloperInterface extends HumanInterface {
    code(): void;
}
```

Here we have an interface called `DeveloperInterface` that extends the `HumanInterface` interface.

Instead of duplicating the properties and methods of the `HumanInterface` interface, we can extend it and add the `code` method.

## Multiple Interfaces

A single class can implement multiple interfaces, this can also be useful if the class is having multiple responsibilities.

Let's see an example:

```ts
interface HumanInterface {
    name: string;
    age: number;
    sayHello(): void;
}

interface DeveloperInterface {
    code(): void;
}

class HumanDeveloper implements HumanInterface, DeveloperInterface {
    name = 'Hasan';
    age = 33;
    sayHello() {
        console.log('Hello');
    }
    code() {
        console.log('Coding...');
    }
}
```

Here we have a class called `HumanDeveloper` that implements the `HumanInterface` and the `DeveloperInterface` interfaces.

## 🎨 Conclusion

In this article, we learned what is an interface, why do we need interfaces, how to define an interface, how to use an interface, interfaces are contracts, interfaces are not classes, extending interfaces, and multiple interfaces.

As this course is not about Typescript, i won't talk about `type` keyword, we can create another series for Typescript.

## ☕♨️ Buy me a Coffee ♨️☕

If you enjoy my articles and see it useful to you, you may [buy me a coffee](https://www.paypal.com/paypalme/hassanzohdy), it will help me to keep going and keep creating more content.

## 😍 Join our community

Join our community on [Discord](https://discord.gg/uBh98KZGGF) to get help and support.

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

* [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
* [Node Js 2023 Course: Node With Typescript, The Ultimate Guide](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)