Do you want to know if to use a Typescript enum or union type? In this tutorial, I will explain everything about Typescript enum vs union type. We will see enum vs. union in Typescript with examples, use cases, and differences.
In TypeScript, Enums are best used for defining a set of named constants (like directions or days of the week), providing an organized way to group related values. Union Types, on the other hand, allow a variable to hold one of several types (like a string or a number), offering more flexibility in your code. Choose Enums for a fixed set of related values and Union Types for variables that may have multiple valid types.
What is TypeScript Enum?
Enums, short for enumerations, are a feature in TypeScript that allows us to define a set of named constants. This type can be numeric or string-based, offering a way to group related values under a single umbrella, making code more readable and maintainable.
Example of TypeScript Enum
enum Direction {
Up = 1,
Down,
Left,
Right
}
// Usage
let go: Direction = Direction.Up;
In this example, Direction
is an enum with four values. Enums start numbering their members starting at 0
. Here, Up
is initialized with 1
, so Down
will be 2
, and so on.
What is TypeScript Union Type?
Union Types in TypeScript are a way to declare a variable that could be one of several types. It’s a powerful feature that allows greater flexibility in your functions and variables.
Example of TypeScript Union Type
type StringOrNumber = string | number;
// Usage
let data: StringOrNumber;
data = "Hello"; // valid
data = 123; // valid
In this example, StringOrNumber
is a Union Type that can be either a string or a number.
Comparing Enums and Union Types
While Enums are about defining a set of named constants, Union Types are more about combining different types in Typescript. Enums offer better code organization for a group of related constants, whereas Union Types offer more flexibility in variable assignment.
Use Cases
- Enum Use Case: Ideal for a set of distinct values that are closely related, like directions, days of the week, or specific states in a process.
- Union Type Use Case: Best suited for variables that can legitimately hold more than one type of value, like a function that can accept both strings and numbers.
Examples
Enum Example
enum Direction {
Up = 1,
Down,
Left,
Right
}
In this example, Direction
is an enum representing four directions. Enums in TypeScript can have numeric values, and here Up
is explicitly set to 1
. The other enum members (Down
, Left
, Right
) are auto-incremented from Up
, getting values 2
, 3
, and 4
respectively. This enum is useful for scenarios where you need to represent a fixed set of options, like directions in a navigation system.
Union Type Example
type StringOrNumber = string | number;
Here, StringOrNumber
is a Union Type that can hold either a string or a number. This is useful in functions or variables where you might want to accept multiple types. For instance, a function could accept a numeric ID or a string username as an argument, both represented by StringOrNumber
.
Here is another example:
type ID = string | number;
let userId: ID;
userId = "user123"; // valid
userId = 123; // valid
enum vs union in Typescript
Feature | Enum | Union Type |
---|---|---|
Definition | A set of named constants | A type that can be one of several types |
Use Case | Grouping related constants | Variables that can hold multiple types |
Initialization | Numeric or string-based values | No initialization, just a type definition |
Flexibility | Less flexible, fixed set of values | More flexible, can combine different types |
Example | enum Colors {Red, Green, Blue} | type StringOrNumber = string | number; |
Conclusion
In TypeScript, both Enums and Union Types have their unique place. Enums are excellent for defining a set of related constants, bringing clarity and structure to your code. On the other hand, Union Types offer the flexibility to handle multiple data types, making your functions and variables more versatile. Understanding when to use each will significantly enhance your TypeScript coding proficiency. I hope you got an idea of “Typescript enum vs union type“.
You may also like:
- Typescript remove quotes from string
- Typescript replace all occurrences in string
- Typescript Get Last Element of Array
- Typescript merge two arrays of objects
I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com