DEV Community

Cover image for How to use TypeScript enums to store Union Types and access them during runtime
Dima Vyshniakov
Dima Vyshniakov

Posted on

1

How to use TypeScript enums to store Union Types and access them during runtime

TypeScript as a programming language has two lexical dimensions: executable code and types system. Usually these two interoperate only during transpilation (a portmanteau of transformation and compilation) step due to the language static nature.

enum is one of the rare exceptions to this rule. It's a unicorn πŸ¦„ able to operate in two dimensions at the same time. This allows the developer multiple opportunities, such as having more readable Union types, being able to access these values from the executable code and while testing. Let's see below.

Use enum for Union Types

We are going to use enum as an advanced replacement for Union Types. Let's imagine, we have a React Component, which accepts a variant prop. The prop should be able to accept success, danger, or warning value. The naive approach to typing this property would be something like below.

import type {FC} from 'react';

type Props = {
    variant?: 'success' | 'danger' | 'warning';
}

const Component: FC<Props> = ({variant}) => {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

String enums allow us a more advanced way of doing this.

enum Variants {
    success = 'success',
    danger = 'danger',
    warning = 'warning',
}

type Props = {
    variant?: keyof typeof Variants;
}
Enter fullscreen mode Exit fullscreen mode

foo = 'foo' reflection allows us to utilize these values, by giving string enums the benefit that they serialize well.

Access enum values during runtime

Now we can use one of the enum values as a default prop value.

const Component: FC<Props> = ({variant = Variants.success}) => {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

The next thing we are going to do is to map enum values to colors. We can do it in a type safe way. Thus, tsc compiler will inform us about missing or excessive values.

const colorMapping = {
    [Variants.success]: 'green',
    [Variants.danger]: 'red',
    [Variants.warning]: 'orange',
}

const Component: FC<Props> = ({variant = Variants.success}) => {
    // ...
    const mainColor = colorMapping[variant] // 'green'
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Use enum values during tests

When the component is finished, we want to make sure that all possible variants are covered by tests. ES runtime sees our string enum as an arbitrary Object, so we can easily extract values into array.

import { Component, Variants } from './Component';

const variants = Object.values(Variants);

describe('Component', () => {
    it.each(variants)('renders Component', variant => {
        render(<Component variant={variant}>foo</Component>);
        expect(screen.getByText('foo')).toBeInTheDocument();
    });
})
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay