Introduction to Interfaces in TypeScript


Introduction

Interfaces are a fundamental part of TypeScript, providing a way to define the shape or contract of objects. They allow you to specify the structure of an object, including its properties and methods, without providing an implementation. In this guide, we'll explore the concept of interfaces and how to use them in TypeScript.


What is an Interface?

An interface is a TypeScript feature that defines a contract specifying which properties and methods an object must have. It serves as a blueprint for creating objects and enforcing consistency in your code.


Defining an Interface

In TypeScript, you can define an interface using the interface keyword.


Example:

interface Person {
firstName: string;
lastName: string;
sayHello(): void;
}

Implementing an Interface

Once you've defined an interface, you can create objects that conform to its structure. An object that implements an interface must provide the required properties and methods.


Example:

const person: Person = {
firstName: "John",
lastName: "Doe",
sayHello() {
console.log("Hello, " + this.firstName + " " + this.lastName);
}
};
person.sayHello(); // Output: Hello, John Doe

Interface for Classes

Interfaces can also be used to define the structure of a class. A class that implements an interface must adhere to the interface's contract.


Example:

class Greeter implements Person {
constructor(public firstName: string, public lastName: string) {}
sayHello() {
console.log("Hello, " + this.firstName + " " + this.lastName);
}
}
const greeter = new Greeter("Alice", "Smith");
greeter.sayHello(); // Output: Hello, Alice Smith

Optional and Readonly Properties

Interfaces can have optional properties denoted by a ?, and readonly properties using the readonly modifier.


Example:

interface Car {
brand: string;
model: string;
year?: number;
readonly vin: string;
}
const myCar: Car = {
brand: "Toyota",
model: "Camry",
vin: "12345",
};
myCar.year = 2022; // Valid
myCar.vin = "54321"; // Error: Cannot assign to 'vin' because it is a read-only property.

Conclusion

Interfaces in TypeScript are a powerful tool for defining contracts and ensuring consistency in your code. Whether used for defining object shapes or class structures, interfaces play a key role in making your code more maintainable and less error-prone by enforcing well-defined structures and behaviors.