Interfaces and Type Aliases
How to define the shape of objects using interface and type, and the differences between them.
🧑🏫 Sabse pehle — simple mein samjho#
Jab tum JavaScript mein object banate ho, toh uska koi fix structure (shape) nahi hota. TypeScript mein tum Interfaces aur Types use karke object ka "Naksha" (blueprint) banate ho. Taaki agar object mein koi property miss ho, ya galat type ki ho, toh TS turant error pakad le. Dono lagbhag same kaam karte hain, par thode chhote differences hain.
Type Aliases (type)#
The type keyword allows you to give a new name to any type, whether it's an object, a primitive, or a complex combination.
// Defining the blueprint for an object
type User = {
name: string;
age: number;
email: string;
};
// Using the type
const user1: User = {
name: "Tarun",
age: 25,
email: "tarun@test.com"
};
Interfaces (interface)#
The interface keyword is specifically designed for declaring the shapes of Objects and Classes.
interface UserData {
name: string;
age: number;
}
const user2: UserData = {
name: "Rana",
age: 26
};
Optional properties (?) and Readonly (readonly)#
Sometimes, certain properties aren't mandatory (like a middle name); you can use ? for them. For properties that shouldn't be modified after creation (like an ID), use the readonly modifier.
interface Product {
readonly id: number; // Cannot be modified after initialization
title: string;
price: number;
description?: string; // Optional property
}
const myMac: Product = {
id: 101,
title: "MacBook",
price: 1500
};
// myMac.id = 102; // ❌ ERROR: Cannot assign to 'id' because it is a read-only property.
Extending (Combining Blueprints)#
If you want to build a larger blueprint based on an existing one:
Extending Interfaces (extends)#
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const myDog: Dog = { name: "Bruno", breed: "Husky" };
Extending Types (& - Intersection)#
type Vehicle = { wheels: number; }
type Car = Vehicle & { brand: string; }
const myCar: Car = { wheels: 4, brand: "Toyota" };
type vs interface — Which one should I use?#
Today, both type and interface are incredibly powerful and can often be used interchangeably. However, here are the standard best practices:
- Use
interface: When defining the shape of Objects or Classes, or when writing libraries (because interfaces with the same name automatically merge together — a feature called "Declaration Merging"). - Use
type: When you need complex types like Unions (type Status = "success" | "error"), Tuples, or when you are aliasing primitive types.
In React, many developers prefer using type for component Props, but using interface is perfectly valid as well!