What in Union Type in Typescript | Union Type | Typescript Tutorial-9
HTML-код
- Опубликовано: 2 окт 2024
- In TypeScript, a union type is a type that allows a value to be one of several specified types. It’s useful when you want to allow a variable to have multiple potential types. You define a union type using the vertical bar (|) to separate each type.
let data: string | number;
data = "Hello World"; // OK
data = 100; // OK
data = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
In this example, the variable data can be either a string or a number, but not any other type like boolean.