Object Literals

1. Welcome and Icebreaker:

  • If you could design an object to represent yourself, what properties would it have?

2. Outline the Session:

  • We’ll learn about object literals in TypeScript: how to define objects with properties and methods.
  • Learning Outcomes: Understand how to create and use objects, and how to type them.
  • Let’s get creative!

3. Concept Explanation:

  • Object Literals are a way to define objects directly in your code using curly braces {}.
  • Objects can have properties (data) and methods (functions).
  • In TypeScript, you can specify the types of properties and methods for better safety and IntelliSense.
  • Syntax:
    const person = {
      name: "Alice",
      age: 30,
      greet: function() {
        console.log(`Hello, my name is ${this.name}`);
      }
    };
    
  • You can also use type annotations for object shapes.

4. Live Coding Demonstration:

// Object literal with properties and a method
const car = {
  make: "Toyota",
  model: "Corolla",
  year: 2020,
  start: function() {
    console.log(`Starting ${this.make} ${this.model}`);
  }
};
car.start();

// Typed object literal
const user: { id: number; username: string; isActive: boolean } = {
  id: 1,
  username: "coder123",
  isActive: true
};
console.log(user);

// Object with method using arrow function (note: `this` is not bound)
const calculator = {
  value: 0,
  add: function(n: number) {
    this.value += n;
  },
  reset: () => {
    // Arrow function: `this` is not the calculator object
    // Avoid using arrow functions for methods that use `this`
    // This will not work as expected
  }
};
calculator.add(5);
console.log(calculator.value); // 5

5. Tasks:

  • Short Exercise:
    1. Create an object book with properties: title (string), author (string), and pages (number).
    2. Add a method describe to book that prints a summary of the book.
    3. Create a typed object student with properties: id (number), name (string), grades (array of numbers).
    4. Add a method to student that calculates and returns the average grade.