Interface in Typescript with Examples

Interface in Typescript with Examples

An interface in TypeScript is a contract that defines the structure of an object. It specifies the properties and methods that an object should have, without providing any implementation details.

One of the main benefits of using interfaces in TypeScript is that they allow for better code organization and maintainability. By defining interfaces for your objects, you can ensure that all objects used in your application have the same structure, making it easier to understand and work with your code.

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

To use an interface, you can create an object that implements the interface, like this:

let person: Person = {
    name: "John Doe",
    age: 30,
    sayHello: () => {
        console.log("Hello!");
    }
};

Interfaces can also be extended, just like classes. It allows you to reuse the properties and methods of an existing interface and add new ones.

interface Employee extends Person {
    salary: number;
    getSalary(): number;
}

In conclusion, interfaces are a powerful feature in TypeScript that allows you to define the structure of your objects and improve code organization. They are easy to use and understand, and they help you to write better and more maintainable code. Start using interfaces in your TypeScript projects and see the benefits for yourself!"