#typescript
#beginner
#objects
#types
Day 4: Objects and Type Aliases
Structuring Data
Welcome to Day 4! Today we move beyond simple lists and start modeling real-world entities using Objects.
Object Types
In JavaScript, objects are dynamic bags of properties. In TypeScript, we define exactly what that bag contains.
let user: { name: string; age: number; isAdmin: boolean } = {
name: "Jack",
age: 30,
isAdmin: true
};
If you try to access a property that doesn’t exist, TypeScript will yell at you.
// console.log(user.email); // Error: Property 'email' does not exist...
Optional Properties
Sometimes a property might not exist. We use the ? symbol to mark it as optional.
let product: {
id: number;
title: string;
description?: string; // Optional
};
product = { id: 1, title: "Laptop" }; // OK
Type Aliases
Writing { name: string; age: number... } everywhere gets messy and repetitive. We can use a Type Alias to create a reusable name for a shape.
type User = {
name: string;
age: number;
isAdmin: boolean;
};
let user1: User = { name: "Alice", age: 25, isAdmin: false };
let user2: User = { name: "Bob", age: 30, isAdmin: true };
Type Aliases can also be used for primitives, unions, and tuples.
type ID = string | number; // Union type (String OR Number)
type Coordinates = [number, number];
Challenge for Today
- Create a file
day4.ts. - Define a
Type AliascalledBookwith:title(string)author(string)publishedYear(number)isAvailable(boolean, optional)
- Create a variable
favoriteBookof typeBook. - Try to assign a number to the
titleproperty and verify the error.
See you on Day 5 for the battle of Interfaces vs. Types!