11. Interfaces & Object Modifiers
Interfaces: The Object Blueprints
In the previous modules, we used type aliases to define object shapes. However, TypeScript provides another, incredibly powerful way to define objects: the Interface. Interfaces are the industry standard for defining object structures, especially in large-scale React applications.
Defining an Interface
An interface strictly defines the contract that an object must adhere to. The syntax looks very similar to a class or an object literal, but without the equals sign.
Interface vs Type: What's the difference?
For basic objects, interface and type do the exact same thing. The primary difference is extendability. Interfaces are designed to be extended (inherited from), just like Object-Oriented classes. Types use intersections (&) which can get messy, while Interfaces use the clean extends keyword.
Optional Properties
In real-world data, some fields are not guaranteed to exist. If you fetch a user from a database, they might not have provided a phone number. We use the Optional Modifier (?) to tell TypeScript that a property is allowed to be missing.
Readonly Properties
Sometimes you want to assign a value to a property when the object is created, but ensure that it can never be changed or mutated afterward (like a database ID or a created timestamp). The readonly modifier enforces this.
Knowledge Check
Ready to test your understanding of 11. Interfaces & Object Modifiers?