LoginSignup
4
2

More than 5 years have passed since last update.

flowtypeでconstantsからEnumっぽいUnion型を生成する

Last updated at Posted at 2018-07-06

下記のようなconstantsがあったとする。

const COLORS = {
  WHITE: 'white',
  BLUE: 'blue',
  BLACK: 'black',
  RED: 'red',
  GREEN: 'green',
};

このconstantsから

type ColorTypes = 'white' | 'blue' | 'black' | 'red' | 'green';

こんなUnion型が生成したかった。調べてみるとちょっと汚いが方法はあった。

/* @flow */

const COLORS = Object.freeze({
  WHITE: 'white',
  BLUE: 'blue',
  BLACK: 'black',
  RED: 'red',
  GREEN: 'green',
});
type ColorsType = $Values<typeof COLORS>;

const Bad: ColorsType = 'yellow'; // error
const Good: ColorsType = 'white'; // ok

これでいける。良い感じ。

ちなみにconstantsとtypeが別ファイルだと機能しなくなる。

export const COLORS = Object.freeze({
  WHITE: 'white',
  BLUE: 'blue',
  BLACK: 'black',
  RED: 'red',
  GREEN: 'green',
});
import { COLORS } from './constants';

type ColorsType = $Values<typeof COLORS>;

const Bad: ColorsType = 'yellow'; // ok
const Good: ColorsType = 'white'; // ok

おそらくObject.freezeでimmutableであることを同一ファイル内じゃないと認識できないっぽい。

4
2
0

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
4
2