Optional Properties and Methods in Object Types

1. Welcome and Icebreaker:

  • If you could make any feature in your favorite app optional, what would it be?

2. Outline the Session:

  • We’ll learn how to define optional properties and methods in TypeScript object types and interfaces.
  • Learning Outcomes: Understand how to use ? to make properties/methods optional and when to use this feature.
  • Let’s explore flexibility in type definitions!

3. Concept Explanation:

  • Optional Properties: Add a ? after the property name to indicate it may or may not be present.
    interface User {
      id: number;
      name: string;
      email?: string; // optional
    }
    
  • Optional Methods: Similarly, methods can be optional.
    interface Logger {
      log?(message: string): void;
    }
    
  • Use Cases:
    • When not all objects will have the same set of properties or methods.
    • Useful for configuration objects, partial updates, or plugin systems.
  • Accessing Optional Properties: Always check for existence before using.

4. Live Coding Demonstration:

interface Config {
  url: string;
  timeout?: number;
  onSuccess?(): void;
}

const config1: Config = {
  url: "https://api.example.com"
};

const config2: Config = {
  url: "https://api.example.com",
  timeout: 5000,
  onSuccess: () => console.log("Success!")
};

function makeRequest(config: Config) {
  console.log(`Requesting: ${config.url}`);
  if (config.timeout) {
    console.log(`Timeout: ${config.timeout}ms`);
  }
  config.onSuccess?.(); // Optional chaining
}

makeRequest(config1);
makeRequest(config2);

5. Tasks:

  • Short Exercise:
    1. Define an interface Profile with properties: username (string), bio (optional string), and a method updateBio (optional, takes a string and returns void).
    2. Create two Profile objects: one with a bio and updateBio, one without.
    3. Write a function that prints the bio if it exists, and calls updateBio if available.