9. Objects & Type Aliases
Defining Complex Structures
Primitives (strings, numbers) and arrays are simple. But real-world applications run on complex objects. A "User" has a name, an email, an age, and a role. We must define the exact "blueprint" of these objects so TypeScript can enforce their structure across our entire codebase.
Inline Object Typing
You can define the shape of an object directly inline next to the variable declaration. This works, but it becomes incredibly messy if you have multiple objects with the same shape.
The Magic of Type Aliases
Instead of writing out the shape every single time, we use the type keyword to create a custom name for our specific object shape. This creates a reusable blueprint.
Optional Properties
In the real world, not all data is mandatory. A user might not want to provide a phone number. If we define the type strictly, TypeScript will error if the phone number is missing. We fix this using the Optional modifier ?.
Structural Typing (Duck Typing)
TypeScript uses a concept called "Structural Typing" (often called Duck Typing: if it walks like a duck and quacks like a duck, it's a duck). TypeScript doesn't care how an object was created; it only cares if the object has the correct properties (the structure) required by the type.
Knowledge Check
Ready to test your understanding of 9. Objects & Type Aliases?