DEV Community

Discussion on: State machine advent: A safer way to type events and state (11/24)

Collapse
 
codingdive profile image
Mikey Stengel

Another way is to create a plain JavaScript object from an array using .reduce() which allows you to define each string only once.

const LIGHT_SWITCH_EVENT = [
  'TOGGLE',
  'SOME_OTHER_EVENT',
].reduce((obj, item) => {
  obj[item] = item;
  return obj;
}, {});

// then use it like this: LIGHT_SWITCH_EVENT.TOGGLE

I'll stick to enums as I think they are much easier to read.