February 3, 2021

How to Create a Union Type From an Array

A tiny TypeScript tip for run-time checks

There reaches a point in everyone's TypeScript journey when they try to use types at run-time. In my case, I wanted to map over each key in a Union to create a list:

type Item = "orange" | "apple" | "pear";

const Food: React.FC = () => (
  <ul>
    {/**
     * ❌ error:
     *   'Item' only refers to a type,
     *   but is being used as a value here
     */}
    {Item.map((item) => (
      <li key={item}>{item}</li>
    ))}
  </ul>
);

Solution

Fortunately, as const is here to help:

// `as const` allows us to define `items` as a readonly array,
// with a type of its *actual* values (i.e. not string[])
const items = ["orange", "apple", "pear"] as const;

type Items = typeof items; // readonly ['orange', 'apple', 'pear']

type Item = Items[number]; // 'orange' | 'apple' | 'pear'

const Food: React.FC = () => (
  <ul>
    {items.map((item) => (
      <li key={item}>{item}</li>
    ))}
  </ul>
);

––– views


Enjoyed this article? Please share and let me know your thoughts.

Copyright © 2021 Joe Bell