Union Types

1. Welcome and Icebreaker:

  • If you could choose to be one of several things for a day, what would your options be?

2. Outline the Session:

  • We’ll learn about union types in TypeScript: how to allow values of different types.
  • Learning Outcomes: Understand how to use | to create flexible types that accept multiple forms.
  • Let’s explore flexibility in type systems!

3. Concept Explanation:

  • Union Types use the | operator to allow a variable to be one of several types.
  • Syntax:
    let value: string | number;
    value = "hello";
    value = 42;
    
  • Useful for function parameters, return types, or variables that can accept more than one type.
  • When using union types, you often need to use type guards (like typeof or Array.isArray) to determine the actual type at runtime.

4. Live Coding Demonstration:

let id: string | number;
id = "abc123";
console.log(id);
id = 789;
console.log(id);

function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(`ID (string): ${id.toUpperCase()}`);
  } else {
    console.log(`ID (number): ${id.toFixed(2)}`);
  }
}
printId("user42");
printId(42);

// Union with arrays
function formatInput(input: string | string[]) {
  if (Array.isArray(input)) {
    return input.join(", ");
  }
  return input;
}
console.log(formatInput(["apple", "banana"]));
console.log(formatInput("orange"));

5. Tasks:

  • Short Exercise:
    1. Declare a variable result that can be a number or a string. Assign both types of values and print them.
    2. Write a function logStatus that takes a parameter of type "success" | "error" | "loading" and prints a message for each status.
    3. Write a function formatValue that takes a string | number and returns a string representation. Use type guards to handle each type.