

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Unions
incomplete
2: Optional Parameters
incomplete
3: Default Parameters
incomplete
4: Literal Types
incomplete
5: Value Unions
incomplete
6: Template Literal Types
incomplete
7: Giant Unions
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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
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.
The .split() method on the - delimiter will be useful for parsing the number part out of a project code.