Union types allow a variable to hold one of several types using the | operator.
Getting Started
What is TypeScript?
Basic Types
Types & Interfaces
Async TypeScript
Promises & Async/Await
TypeScript
Intermediate
FREE
Union Types
Lesson 1 of 17
Intermediate
Interactive
Syntax
TYPESCRIPT
let id: string | number; id = "ABC123"; id = 123;
Union and Literal Types
TYPESCRIPT
type ID = string | number; function printId(id: ID): void { console.log(`ID: ${id}`); } printId(101); printId("abc-123"); type Direction = "up" | "down" | "left" | "right"; function move(dir: Direction): void { console.log(`Moving ${dir}`); } move("up");
Practice
1
Exercise
Practice this concept.
Answer
Write the code as shown above.
Quick Quiz
1
What did you learn?
This covers the basics.
Interview Questions
It is a fundamental TypeScript feature.