Module 28: Interfaces and Type Design
Type aliases and when to use which
🏠The everyday picture
Two kinds of labels in an office: one kind for document folders (always describing a folder), and a general labelling machine that can name anything, from a folder to a colour code.
📘What it really is
- A type alias names any type with
type:
type Paise = number;
type Status = "pending" | "paid" | "cancelled";
type Point = { x: number; y: number };
- Interfaces can only describe object shapes; type aliases can name anything: unions, literal types, objects, functions:
type PriceRule = (price: Paise) => Paise;
- Combining object types:
- interfaces use
extends; -
type aliases use
&(an intersection):type Admin = User & { permissions: string[] };. -
Which to use? For object shapes, either works; many teams use
interfacefor objects andtypefor everything else. Pick one convention and keep to it. -
type Paise = numberdocuments meaning but doesn't stop you passing rupees. It's a name, not a new kind of number.
🖱️Try it
In types.ts, add type Paise = number;, type Status = ... and type PriceRule = (price: Paise) => Paise;.
Update Product.price to use Paise, and type your makeDiscount function from Module 23 so that it returns a
PriceRule.
✅Quick check
Can an interface describe a union like "S" | "M" | "L"?
Show the answer
No. Use a type alias for unions.
Does type Paise = number stop you passing a value in rupees?
Show the answer
No. It's just another name for number; it documents meaning only.
