How to useUnion Types in Typescript
Union types allow flexibility by combining multiple types with the |
operator. They are more open-ended, permitting any string value within the specified set without a predefined enum structure.
Example: In this example, we define types Color
and Days
with specific string values. We assign values to variables myColor
and today
, logging their outputs, resulting in “FF0000” and “Wed” respectively.
type Color = "FF0000" | "00FF00" | "0000FF";
type Days = "Mon" | "Tue" | "Wed" | "Thu" | "Fri";
const myColor: Color = "FF0000";
const today: Days = "Wed";
console.log(myColor); // Output: "FF0000"
console.log(today); // Output: "Wed"
Output:
FF0000
Wed
How to Create an Enum With String Values in TypeScript ?
To create an enum with string values in TypesScript, we have different approaches. In this article, we are going to learn how to create an enum with string values in TypesScript.
Below are the approaches used to create an enum with string values in TypesScript:
Table of Content
- Approach 1: Using Enums
- Approach 2: Using Union Types
- Approach 3: Using Object Mapping
- Approach 4: Using String Literal Types with Const Assertion