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

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!

Top comments (0)