Interface

Interfaces in TypeScript are used to define agreements for objects. They can contain properties, methods, and method signatures. Interfaces can be implemented by classes to enforce a specific structure and ensure that the class adheres to the contract defined by the interface. Interfaces support multiple inheritance, where a class can implement multiple interfaces.

Syntax

interface MyInterface {
    // Interface properties and methods
}

Example

In this example, we will see the implementation of the Interface.

 

Javascript




// Interface.ts
interface Person {
    name: string;
    age: number;
}
  
const person: Person = {
    name: "John Doe",
    age: 25,
};
  
console.log(person.name);
console.log(person.age);


Output

"John Doe"    // person.name
25                  // person.age

TypeScript Interface vs Type Statements

In TypeScript, both “interface” and “type” statements are used to define the shape or structure of an object or a type. They provide a way to define custom types and enforce type checking in TypeScript code. However, there are some differences between the two.

Similar Reads

Interface

Interfaces in TypeScript are used to define agreements for objects. They can contain properties, methods, and method signatures. Interfaces can be implemented by classes to enforce a specific structure and ensure that the class adheres to the contract defined by the interface. Interfaces support multiple inheritance, where a class can implement multiple interfaces....

Type

...

Difference between Interface and type Statements

Types in TypeScript are used to define custom types that can be used to represent a shape or structure of an object. Types can represent any valid type in TypeScript, including primitive types, union types, intersection types, etc. Types can be used for creating aliases of existing types, making complex types more readable and reusable....