DEV Community

Cover image for Simplifying Union Types and Arrays in TypeScript
mktoho
mktoho

Posted on

Simplifying Union Types and Arrays in TypeScript

When working with TypeScript, you might find yourself needing to define a union type and an array containing all of the possible values of that type. A common approach is to write something like this:

type Taste = 'しょうゆ' | 'みそ' | 'とんこつ';
const tastes = ['しょうゆ', 'みそ', 'とんこつ'];
Enter fullscreen mode Exit fullscreen mode

At first glance, this seems fine. However, there's a hidden problem here: every time you want to change or add an option, you need to update both the Taste union type and the tastes array. This duplication of effort can lead to mistakes and makes maintaining the code more tedious.

Luckily, there's a way to simplify this by reducing redundancy. By using the as const assertion and typeof in TypeScript, you can consolidate the definition of both the union type and the array into one place. Here's how you can refactor the above code:

const tastes = ['しょうゆ', 'みそ', 'とんこつ'] as const;
type Taste = (typeof tastes)[number];
Enter fullscreen mode Exit fullscreen mode

This approach has several benefits:

  1. Single Source of Truth:

    You only define the list of values once, in the tastes array. The Taste type is automatically derived from this array, so if you ever need to update the list, you only have to do it in one place.

  2. Type Safety:

    By using as const, TypeScript treats the tastes array as a tuple with literal types instead of just a string array. This ensures that the Taste type remains accurate and aligned with the values in tastes.

  3. Better Maintenance:

    Since the Taste type is generated from the array, there’s no risk of mismatch between the type and the actual values. This reduces the potential for bugs and makes the code easier to maintain.

Example Use Case

Now, whenever you use the Taste type in your code, it’s guaranteed to match the values in the tastes array:

function describeTaste(taste: Taste): string {
  switch (taste) {
    case 'しょうゆ':
      return 'Savory soy sauce flavor.';
    case 'みそ':
      return 'Rich miso flavor.';
    case 'とんこつ':
      return 'Creamy pork broth flavor.';
    default:
      return 'Unknown taste';
  }
}

const allTastes: Taste[] = tastes; // Safe, because they match the type!
Enter fullscreen mode Exit fullscreen mode

This pattern not only improves your code’s readability but also ensures that it’s less error-prone, especially when dealing with multiple values that need to be kept in sync.

By embracing this strategy, you can make your TypeScript code more maintainable and scalable. This is particularly useful when you're dealing with large sets of values or when your codebase grows over time.

Top comments (2)

Collapse
 
sidra24 profile image
sidra khan

When working with TypeScript, managing union types and arrays can lead to redundancy and maintenance challenges. For example, if you have a Taste union type and an array tastes, any change to the array requires manually updating both the type and the array. A more efficient approach involves using as const and typeof, which allows TypeScript to infer the literal values of the array and automatically derive the corresponding type. This not only reduces duplication but also minimizes the potential for errors. You know artificial intelligence innovations are rapidly transforming industries across the board. From healthcare to finance, AI is streamlining processes, improving decision-making, and enabling personalized experiences.

Collapse
 
hughes12 profile image
Crist Chris

When using TypeScript, defining a union type and an array can be tedious due to redundancy. For example, with the type Taste and the array tastes, any change requires updating both. Instead, you can simplify this process with as const and typeof. This approach reduces errors, much like how players in friday night funkin must adapt strategies to win. Streamlining code enhances efficiency, making development smoother.