Welcome back! I am Mihir, and in this lesson we will learn interfaces in TypeScript.
An interface describes the shape of an object.
Basic Interface
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: "Mihir",
email: "mihir@example.com",
};The object must match the interface structure.
Missing Properties
Invalid:
const user: User = {
id: 1,
name: "Mihir",
};email is required, so TypeScript shows an error.
Optional Properties
Use ? to make a property optional.
interface Product {
id: number;
name: string;
description?: string;
}Valid:
const product: Product = {
id: 101,
name: "Mouse",
};Readonly Properties
interface Order {
readonly id: number;
total: number;
}
const order: Order = {
id: 5001,
total: 999,
};You can update total.
order.total = 1099;But you cannot update id.
order.id = 5002;Interfaces with Methods
Interfaces can describe methods too.
interface Logger {
log(message: string): void;
}
const consoleLogger: Logger = {
log(message) {
console.log(message);
},
};The object must provide a log method that accepts a string and returns nothing.
Function Properties in Interfaces
You can also write methods as function properties.
interface Calculator {
add: (a: number, b: number) => number;
}
const calculator: Calculator = {
add: (a, b) => a + b,
};Both styles are common.
Extending Interfaces
An interface can build on another interface.
interface Person {
name: string;
}
interface Employee extends Person {
employeeId: number;
}
const employee: Employee = {
name: "Mihir",
employeeId: 101,
};Employee has both name and employeeId.
Declaration Merging
Interfaces with the same name can merge.
interface Settings {
theme: string;
}
interface Settings {
language: string;
}
const settings: Settings = {
theme: "dark",
language: "en",
};This is called declaration merging.
Quick Recap
- Interfaces describe object shapes.
- They support required, optional, and readonly properties.
- They can describe methods and function properties.
- Interfaces can extend other interfaces.
- Interfaces with the same name can merge.
Next up, we compare Interface vs Type → so you know which one to choose in real projects.