Interfaces are a powerful feature in TypeScript that define the structure of objects. They serve as contracts, ensuring that objects adhere to a specific shape.
An interface in TypeScript is a way to define a type that describes the properties and methods an object should have. It's a blueprint for object structures, promoting code consistency and type safety.
To declare an interface, use the interface
keyword followed by the interface name and its members:
interface Person {
name: string;
age: number;
greet(): void;
}
You can then use this interface to type-check objects:
const john: Person = {
name: "John Doe",
age: 30,
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
Interfaces can have optional properties, marked with a question mark:
interface Car {
make: string;
model: string;
year?: number;
}
This allows for flexibility when implementing the interface. For more details on optional properties, check out the Optional Properties guide.
You can make properties immutable using the readonly
modifier:
interface Point {
readonly x: number;
readonly y: number;
}
This prevents accidental modification of the properties after initialization. Learn more about this in the Readonly Properties section.
Classes can implement interfaces using the implements
keyword:
class Student implements Person {
constructor(public name: string, public age: number) {}
greet() {
console.log(`Hi, I'm ${this.name}, a student.`);
}
}
This ensures that the class adheres to the structure defined by the interface. For a deeper dive, visit the Implementing Interfaces guide.
Interfaces are a cornerstone of TypeScript, providing robust type checking and improving code organization. They offer a flexible way to define object structures and promote code reusability.
As you delve deeper into TypeScript, you'll find interfaces invaluable for creating maintainable and scalable code. To explore more advanced concepts, check out Extending Interfaces and Interfaces vs Type Aliases.