Ts Union
# TypeScript Union Types
In TypeScript, a **Union Type** allows a variable, function parameter, or return value to hold values of multiple different types. This is highly useful when a value can legitimately be more than one type (for example, a unique identifier that could be either a `string` or a `number`).
By using union types, you can write flexible code while still maintaining strict type safety.
---
## Syntax
You can define a union type by separating the allowed types with a vertical pipe symbol (`|`).
```typescript
Type1 | Type2 | Type3
```
> **Note**: A variable declared with a union type can only be assigned values of the specified types. Assigning any other type will result in a compilation error.
---
## Basic Usage
Here is a simple example of declaring a variable that can accept either a `string` or a `number`.
### TypeScript Example
```typescript
let val: string | number;
val = 12;
console.log("Numeric value: " + val);
val = "YouTip";
console.log("String value: " + val);
```
### Compiled JavaScript
When compiled, the TypeScript type annotations are removed, resulting in standard JavaScript:
```javascript
var val;
val = 12;
console.log("Numeric value: " + val);
val = "YouTip";
console.log("String value: " + val);
```
### Output
```text
Numeric value: 12
String value: YouTip
```
### Type Safety Violation
If you attempt to assign a type that is not part of the union declaration, TypeScript will throw a compilation error:
```typescript
let val: string | number;
val = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
```
---
## Union Types as Function Parameters
Union types are commonly used as function parameters to allow functions to accept different formats of data. Inside the function, you can use **type narrowing** (such as the `typeof` operator) to determine the actual type of the argument at runtime and handle it accordingly.
### TypeScript Example
```typescript
function display(name: string | string[]) {
if (typeof name === "string") {
console.log(name);
} else {
for (let i = 0; i < name.length; i++) {
console.log(name);
}
}
}
// Passing a single string
display("YouTip");
console.log("--- Printing Array ---");
// Passing an array of strings
display(["Google", "Taobao", "Facebook"]);
```
### Compiled JavaScript
```javascript
function display(name) {
if (typeof name === "string") {
console.log(name);
}
else {
var i;
for (i = 0; i < name.length; i++) {
console.log(name);
}
}
}
display("YouTip");
console.log("--- Printing Array ---");
display(["Google", "Taobao", "Facebook"]);
```
### Output
```text
YouTip
--- Printing Array ---
Google
Taobao
Facebook
```
---
## Union Types with Arrays
You can also declare arrays that can hold different types of arrays, or arrays where individual elements can be of different types.
### 1. Array of One Type OR Another Type
If you want an array to be *either* an array of numbers *or* an array of strings, use the following syntax:
```typescript
let arr: number[] | string[];
let i: number;
// Assigning a numeric array
arr = [1, 2, 4];
console.log("** Numeric Array **");
for (i = 0; i < arr.length; i++) {
console.log(arr);
}
// Assigning a string array
arr = ["Google", "Taobao", "Facebook"];
console.log("** String Array **");
for (i = 0; i < arr.length; i++) {
console.log(arr);
}
```
### 2. Array with Mixed Elements (Alternative)
If you want a single array to contain a mix of both numbers and strings simultaneously, place the union type inside parentheses before the array brackets:
```typescript
// An array that can contain both numbers and strings together
let mixedArr: (number | string)[] = [1, "YouTip", 2, "TypeScript"];
```
YouTip