Module 28: Interfaces and Type Design
Interfaces
🏠The everyday picture
A standard admission form that every school in a district uses. Once the form is agreed, everyone knows exactly which details a student record has.
📘What it really is
- An interface gives a name to the shape of an object:
interface Product {
id: string;
name: string;
category: Category;
price: number; // in paise
stock: number;
}
- Use it everywhere a product appears:
function describe(product: Product): string { ... }
const products: Product[] = [ ... ];
-
Now TypeScript checks every product: a missing
stockor a misspeltpriseis an error, and autocomplete offers each property. -
Interfaces can build on each other with
extends:
interface DigitalProduct extends Product {
downloadUrl: string;
}
- Comments above properties (like
// in paise) show up when you hover in VS Code. Use them for units and rules. - Interfaces are your data model (Module 21, Lesson 5) written down in a form the computer checks.
🖱️Try it
Create types.ts. Write interfaces for Product, Customer (id, name, phone, city) and OrderLine (productId,
quantity). Use Product[] for your products array in app.ts, and deliberately leave out a property from one
product to see the error.
✅Quick check
What happens if a product object is missing a property its interface requires?
Show the answer
TypeScript reports an error, before the code runs.
Why write // in paise above price?
Show the answer
It records the unit, and appears when hovering, preventing someone treating it as rupees.
