#typescript
#beginner
#interfaces
Day 5: Interfaces vs. Type Aliases
Defining Shapes
Welcome to Day 5! Yesterday we learned about type. Today we introduce its sibling: interface.
What is an Interface?
An interface is another way to name an object type.
interface UserInterface {
name: string;
age: number;
}
const user: UserInterface = {
name: "Jack",
age: 30
};
Interface vs. Type: Key Differences
For 90% of cases, they act the same. But here are the nuances:
1. Implementation
Interfaces are primarily designed to define the shape of objects that can be extended or implemented by classes (more on classes in Phase 2).
2. Declaration Merging (Interface only)
If you declare an interface twice, they merge. This is useful for extending third-party libraries.
interface Window {
title: string;
}
interface Window {
ts: TypeScriptAPI;
}
// The resulting Window interface has BOTH title and ts.
Types cannot do this.
3. Unions (Type only)
Interfaces cannot represent a union (e.g., this OR that). Types can.
type Status = "success" | "failure"; // Interface can't do this
Which One Should You Use?
- Use
interfacewhen defining the shape of an object, especially if you’re writing a library or want object-oriented inheritance. - Use
typefor unions, primitives, tuples, or simple object shapes.
My Rule of Thumb: Start with type. If you need declaration merging or class implementation, switch to interface.
Challenge for Today
- Create a
typeforCarwithmakeandmodel. - Create an
interfaceforBicyclewithbrandandgearCount. - Create objects for both.
- Try to “merge” the
Bicycleinterface by defining it again with a new propertycolorand see if your object requires it.
See you on Day 6!