Concept Explanation
In TypeScript, you need a way to describe what your objects look like. You have two main tools: Interfaces and Types.
- Interface: Think of this as a "Contract" for an object. "Every User MUST have an ID and a Name."
- Type Alias: Think of this as a "NickName" for a specific set of rules.
Syntax or Core Structure
Interface (Extendable)
interface User {
id: number;
name: string;
}
interface Admin extends User {
role: 'super' | 'editor';
}
Type Alias (Flexible)
type Status = "pending" | "success" | "error";
type ID = string | number;
const myId: ID = 42;
const myStatus: Status = "success";
Which Should I Use?
The rule of thumb most teams follow: use interface for object shapes, type for everything else.
interfacecan be reopened — declare it twice and TypeScript merges them (handy for extending library types).typecan express things interfaces can't: unions (A | B), tuples ([number, string]), and mapped types.- Both compose: interfaces use
extends; types use the&intersection operator.
Common Mistakes
- Union in an Interface: You can't write
interface X = A | B. Unions need atype. - Accidental Merging: Declaring the same
typetwice is an error; declaring the sameinterfacetwice silently merges them — surprising if you didn't mean it. - Overusing Optional: Marking everything
?optional defeats the safety. Only mark what's truly optional.
Best Practices
- Be Consistent: Pick one style per project so the codebase reads uniformly.
- Model the Domain: Name shapes after real concepts (
Order,Invoice) rather than genericData1. - Prefer Unions for State:
type Status = "loading" | "done"makes invalid states impossible to represent.
Practice Exercises
- The Contract: Create an
interface Productwith a name, price, and an optional description. - The Extender: Create an interface
ElectronicProductthat extendsProductand adds avoltageproperty. - The Union: Create a
type PaymentMethodthat can only be "CreditCard", "PayPal", or "Bitcoin".