TypeScript Interfaces

TypeScript tutorial

🧩 TypeScript Interfaces

In TypeScript Interfaces is used to define the structure (shape) of an object.

It tells TypeScript what properties and methods an object must have.

Interfaces are especially powerful for object-oriented design, APIs, and large projects.

1️⃣ Basic Interface

interface User {
id: number;
name: string;
age: number;
}
let user: User = {
id: 1,
name: “Sanjit”,
age: 25
};

✔ All properties are required
❌ Missing or extra properties cause an error

2️⃣ Optional Properties (?)

interface Student {
rollNo: number;
name: string;
email?: string;
}
let s1: Student = {
rollNo: 101,
name: “Rahul”
};

3️⃣ Readonly Properties

Once set, cannot be changed.

interface Product {
readonly id: number;
name: string;
price: number;
}
let item: Product = {
id: 1,
name: “Laptop”,
price: 50000
};

// item.id = 2 ❌ Error

4️⃣ Interface with Methods

interface Person {
name: string;
greet(): void;
}
let person: Person = {
name: “Amit”,
greet() {
console.log(“Hello!”);
}
};

5️⃣ Interface for Function Types

interface Add {
(a: number, b: number): number;
}
let sum: Add = (x, y) => x + y;

6️⃣ Interface with Arrays

interface Employee {
id: number;
name: string;
}
let employees: Employee[] = [
{ id: 1, name: “Amit” },
{ id: 2, name: “Rahul” }
];

7️⃣ Extending Interfaces

One interface can inherit another.

interface Person {
name: string;
}
interface Employee extends Person {
empId: number;
}

let emp: Employee = {
name: “Sanjit”,
empId: 1001
};

8️⃣ Interface Declaration Merging ⭐

Interfaces can be merged automatically.

interface Car {
brand: string;
}
interface Car {
model: string;
}

let myCar: Car = {
brand: “Toyota”,
model: “Innova”
};

⚠️ This is not possible with type aliases.

9️⃣ Interface vs Type Alias

FeatureInterfaceType
Object Shape✅ Yes✅ Yes
Declaration Merging✅ Yes❌ No
Extendingextends&
Union Types❌ No✅ Yes
Best ForObjects & classesComplex types

📌 Rule of Thumb

  • Use interface for object structures & public APIs

  • Use type for unions, primitives, functions

🔑 Interfaces Summary

FeatureExample
Basicinterface A {}
Optionalprop?: type
Readonlyreadonly prop
Methodsmethod(): void
Extendinterface B extends A
MergeSame name interfaces

⭐ Best Practices

✔ Use interfaces for object contracts
✔ Prefer interfaces with classes & APIs
✔ Use readonly for immutability
✔ Keep interfaces small and focused

You may also like...