配列からユニオン型を作成する方法


Originally published at joebell.co.uk on 3rd February 2021


実行時に型を使用しようとすると、みんなのタイプスクリプトの旅のポイントに達する.私の場合、 Union の各キーをマップしてリストを作成したかった.
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>
);

解決策
幸いにも、 as const は以下の通りです.
// `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>
);