capypad
0 day streak
typescript / beginner
Snippet

Basic Union Types

Union types allow a variable to hold values of multiple different types, providing flexibility while still maintaining type safety.

snippet.ts
typescript
1
2
3
let id: number | string;
id = 101;
id = "ID-101";
Breakdown
1
let id: number | string;
The pipe symbol (|) allows the variable 'id' to be either a number or a string.
2
id = 101;
Assigning a number is valid because of the union type.
3
id = "ID-101";
Assigning a string is also valid for the same variable.