Objects, Interfaces and Type Aliases
Most real data is objects: a product, a user, an order. An interface describes the shape of an object - which properties it has and their types.
Interfaces describe the shape of your data once - a product, a user, an order - and every function using that data gets checked against it. If you rename a field, TypeScript shows every place that needs updating.
Example
type aliases
type gives a name to any type, not just objects. For object shapes, interface and type are almost the same - pick one style per project.
Example
Extending an interface
Example
Arrays of objects
Example
Key points
- An interface describes an object's shape.
- Use ? for optional and readonly for fixed properties.
- extends builds on another interface.
📝 Test yourself
1. What does an interface describe?
2. What does readonly do on a property?
3. Fill in the keyword so Seller gets all of User's properties:
interface Seller User { gstin: string }
