#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

  1. Create a file day4.ts.
  2. Define a Type Alias called Book with:
    • title (string)
    • author (string)
    • publishedYear (number)
    • isAvailable (boolean, optional)
  3. Create a variable favoriteBook of type Book.
  4. Try to assign a number to the title property and verify the error.

See you on Day 5 for the battle of Interfaces vs. Types!