In TypeScript, interfaces are used to define the structure of an object. They provide a way to create a contract in which an object must adhere to a specific shape, specifying the properties it must have, along with their respective types. Interfaces can also define the method signatures that an object should implement.
Using interfaces helps to enforce a consistent structure across different parts of the codebase and provides a level of abstraction that allows for easier maintenance and readability. It also facilitates reusability by enabling multiple objects to adhere to the same interface, promoting a more modular and scalable design.
interface Person {
name: string;
age: number;
greet: () => void;
}
class Student implements Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
const newStudent = new Student('Alice', 20);
newStudent.greet(); // Output: Hello, my name is Alice and I'm 20 years old.