2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptにおけるEnumと定数Mapの違い

Last updated at Posted at 2017-11-28

もしあなたがReduxアプリを書いているなら、次のようなケースに遭遇するかもしれません。

// @actions.ts
export type Actions = {
  readonly type: Action
}

export enum Action1 {
  FETCH_DATAS = 'FETCH_DATAS',
  RECEIVE_DATAS = 'RECEIVE_DATAS',
}

export const Action2 = {
  FETCH_DATAS: 'FETCH_DATAS',
  RECEIVE_DATAS: 'RECEIVE_DATAS',
}



// @reducers.ts
import {Actions, Action1, Action2} from './reducers'
...

Action1, 2は一見等価のように見えますが、次のような明確な違いがあります。

Action1.FETCH_DATAS = 'FOO' // Error
Action1.FOO = 'FOO' // Error
Action2.FETCH_DATAS = 'FOO' // NOT Error
Action2.FOO = 'FOO' // Error

つまり「enumの方が不変性(Immutable)の保存において優れている」と言え、個人的には「enumの使用を推奨」しています。

2
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?