LoginSignup
10
10

More than 5 years have passed since last update.

TypeScript での文字列 Union 型を enum 代わりに利用するテクニック

Last updated at Posted at 2019-04-04

概要

コンパイラによる誤り検出もできて、テキストエディタ/IDEよる入力補完の支援も得られて、外部からの入力値チェックも行える、文字列 Union 型を enum 代わりに利用するテクニックの紹介

定義例

const dogSource = Object.freeze
(
    {
        "Borzoi": null,
        "Poodle": null,
        "Retriever": null,
        "Mastiff": null,
        "Hot": null,
    }
);
type DogEnum = keyof typeof dogSource; // "Borzoi" | "Poodle" | "Retriever" | "Mastiff" | "Hot"
const dogList = Object.keys(dogSource); // [ "Borzoi", "Poodle", "Retriever", "Mastiff", "Hot" ]

利用例1(代入)

const borzoi: DogEnum = "Borzoi"; // OK
const poodle: DogEnum = "Poodle"; // OK
const mainecoon: DogEnum = "Mainecoon"; // NG(コンパイルエラー)

利用例2(入力値チェック)

const isValidDog = (value :string): boolean => 0 <= dogList.indexOf(value);

const isValidRetriever = isValidDog("Retriever"); // true;
const isValidMainecoon = isValidDog("Mainecoon"); // false;

利用例3(値比較)

const dogValue: DogEnum = getDog();
const isBorzoi = "Borzoi" === dogValue; // OK
const isMainecoon = "Mainecoon" === dogValue; // NG(コンパイルエラー)

利用例4(switch文)

const dogValue: DogEnum = getDog();
switch(dogValue)
{
case "Borzoi": // OK
    console.log("Bow-wow!");
    break;
case "Mainecoon": // NG(コンパイルエラー)
    console.log("Meow!");
    break;
}

入力補完について

VS Code のようなエディタを利用していれば、上記利用例の OK/NG の箇所は入力補完してくれてますので、そもそも間違わずに済みます。

10
10
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10