DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for 8-TS OOP: Interfaces: Contracts
Hasan Zohdy
Hasan Zohdy

Posted on

8-TS OOP: Interfaces: Contracts

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:

interface HumanInterface {
    name: string;
    age: number;
}
Enter fullscreen mode Exit fullscreen mode

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:

class Human implements HumanInterface {
    name = 'Hasan';
    age = 33;
}
Enter fullscreen mode Exit fullscreen mode

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

We can also define methods in an interface:

interface HumanInterface {
    name: string;
    age: number;
    sayHello(): void;
}
Enter fullscreen mode Exit fullscreen mode

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:

class Human implements HumanInterface {
    name = 'Hasan';
    age = 33;
    sayHello() {
        console.log('Hello');
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's see another method that has parameters:

interface HumanInterface {
    name: string;
    age: number;
    sayHello(name: string): void;
}
Enter fullscreen mode Exit fullscreen mode

Now let's implement the interface in a class:

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

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.

interface PaymentInterface {
    pay(amount: number): boolean;
}
Enter fullscreen mode Exit fullscreen mode

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

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we can use these classes in our Order class:

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();
}
Enter fullscreen mode Exit fullscreen mode

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:

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

interface DeveloperInterface extends HumanInterface {
    code(): void;
}
Enter fullscreen mode Exit fullscreen mode

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:

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...');
    }
}
Enter fullscreen mode Exit fullscreen mode

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, it will help me to keep going and keep creating more content.

😍 Join our community

Join our community on Discord 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

Packages & Libraries

React Js Packages

Courses (Articles)

Top comments (0)

12 Gorgeous UI Components for Your Design Inspiration

12 Gorgeous UI components for your design inspiration: cards, text, buttons, checkboxes, icons, loaders and menus.