We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Unions

As someone that writes a lot of Go, union types are the thing I'm most jealous of in TypeScript. I love them.

Union types use the pipe symbol (|) and allow you to specify that a value can be one of several types.

// userId is a string OR a number
let userId: string | number;
userId = "user_42";
userId = 42;

Unions are perfect for when a value could be one of several types. One really cool thing about TypeScript is that conditional checks actually change the type of a variable. This is called "type narrowing". Take a look:

function safeSquare(val: string | number): number {
  if (typeof val === "string") {
    val = parseInt(val, 10);
  }
  // now val is only a number
  return val * val;
}

let result = safeSquare("5");
console.log(result);
// 25

result = safeSquare(5);
console.log(result);
// 25

Assignment

At Support.ai, we're upgrading our ticket processing system to handle different types of ticket identifiers. Our clients use both numeric IDs (like 42) and project codes (like "SUPPORT-123"), and our system needs to process both formats uniformly.

Tips

The .split() method on the - delimiter will be useful for parsing the number part out of a project code.