LoginSignup
2
1

More than 3 years have passed since last update.

悪名高いTypeScriptのenumなしでActionを定義する

Posted at

reduxやuseRecucerで定義するActionですがenumを使うと簡単に定義できるんですがenumはデメリットが多く使わないようにするのがベストプラクティスのようになっています。

個人的には別にどうでもいいかと思うんですがenum使わないで定義する方法を試してみたので載せておきます。

TypeScriptのenumを使わないでreducerを定義

ここでのポイントはas constです。
このキーワードはリテラルの型を保持してくれる効果があります。

const x = {foo: 1}; // {foo: number} 型になってしまう。

const x = {foo: 1} as const; // {foo: 1} 型を保ってくれる。

そして定義したreducerがこちらです。

type State = {
  foo: string;
  bar: number;
};

export const ActionNames = {
  SET_FOO: 'SET_FOO',
  SET_BAR: 'SET_BAR'
} as const;

type Action =
  | {
      type: typeof ActionNames.SET_FOO;
      payload: string;
    }
  | {
      type: typeof ActionNames.SET_BAR;
      payload: number;
    };

export const reducer = (state: State, action: Action) => {
  switch (action.type) {
    case ActionNames.SET_FOO: {
      return {
        ...state,
        foo: action.payload
      };
    }
    case ActionNames.SET_BAR: {
      return {
        ...state,
        bar: action.payload
      };
    }
    default:
      throw new TypeError();
  }
};

せっかくenum用意してくれてるのに残念ですね...

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