In TypeScript, an interface is a powerful way to define the structure of an object. Interfaces allow you to specify the types of properties and methods that an object can have. They provide a way to define contracts within your code, ensuring that certain classes or objects adhere to specific structures and types.
Defining an Interface
An interface is defined using the interface
keyword followed by the interface name. Inside the interface, you define properties and methods with their respective types.
interface Person {
name: string;
age: number;
greet(): void;
}
In this example:
Person
is an interface with three members: name
, age
, and greet
.
name
and age
are properties of type string
and number
, respectively.
greet
is a method that returns void
.
Using Interfaces
You can use interfaces to type-check objects, ensuring they adhere to the defined structure.
const person: Person = {
name: "Alice",
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
},
};
person.greet(); // Output: Hello, my name is Alice
In this example, the person
object conforms to the Person
interface, so TypeScript does not raise any type errors.
Implementing Interfaces in Classes
Classes can implement interfaces to ensure they meet the required structure and behavior.
class Employee implements Person {
constructor(public name: string, public age: number) {}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const employee = new Employee("John", 40);
employee.greet(); // Output: Hello, my name is John
In this example:
The Employee
class implements the Person
interface.
The class provides implementations for the name
, age
, and greet
members as required by the Person
interface.
Optional Properties
Interfaces can define optional properties using the ?
symbol.
interface Car {
brand: string;
model: string;
year?: number; // Optional property
}
const myCar: Car = {
brand: "Toyota",
model: "Corolla",
};
In this example, year
is an optional property, so objects adhering to the Car
interface can include year
but are not required to.
Readonly Properties
Interfaces can define readonly properties that cannot be changed after initialization.
interface Book {
readonly title: string;
author: string;
}
const myBook: Book = {
title: "TypeScript Guide",
author: "John Taylor",
};
// myBook.title = "New Title"; // Error: Cannot assign to 'title' because it is a read-only property.
In this example, title
is a readonly property, so any attempt to modify it will result in a compile-time error.
Extending Interfaces
Interfaces can extend other interfaces, allowing you to build on existing structures.
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const myDog: Dog = {
name: "Buddy",
breed: "Golden Retriever",
};
In this example:
Animal
is an interface with a name
property.
Dog
extends Animal
, adding a breed
property.
myDog
is an object that conforms to the Dog
interface, including both name
and breed
.