Search code examples
typescriptstatemobx-state-tree

mobx-state-tree literal array


is it possible to create literal array type in MST? It should be an equivalent to

type Interval = ['1min', '5min'];

here is an example of code which throw an error

type Interval = '1min' | '5min';

export interface AppStore {
  config: {
    intervals: ['1min', '5min']
  },
  search: {
    symbol: string;
    interval: string;
    dataTypes: string[];
  }
}

const appStore = types
  .model<AppStore>('appStore', {
    config: types.model({
      intervals: types.array(
        types.literal<Interval>('1min'),
        types.literal<Interval>('5min')
      ),
    }),
    search: types.model({
      dataTypes: types.array( types.string ),
      interval: types.union(
        types.literal<Interval>('1min'),
        types.literal<Interval>('5min')
      ),
      symbol: types.string,
    }),
  })

the types.array() expect to have one argument so is it even possible? No luck with MST documentation https://github.com/mobxjs/mobx-state-tree#types-overview


Solution

  • can you elaborate a bit, are you looking for an array type, or a tuple type? In other words, is ["1min"], or ["1min", "5min", "1min"] also acceptable?

    If that is acceptable, types.array(types.union(types.literal("1min"), types.literal("5min")) should do the trick (you was close!). Or simpler: types.array(types.enum(["1min", "5min"])))

    If you are looking for a tuple type, that is not yet implemented: see https://github.com/mobxjs/mobx-state-tree/issues/805