使用String Enum为接口提供索引

时间:2017-11-18 19:15:17

标签: typescript

在Typescript中,我想利用我的字符串枚举

export const enum MutationKeys {
    registerUser = 'registration/REGISTER',
    registerUserCompleted = 'registration/REGISTER_COMPLETED'
}

这样它的字符串值就像这样对象提供了类型检查约束:

const mutations: IDictionary<VuexMutation> = {
    ['registration/REGISTER'](state, payload) {
        state.registration = {
            meta: {
                serverValidated: false
            },
            value: payload
        };
    },
    ['registration/REGISTER_COMPLETED'](state) {
        state.registration.meta.serverValidated = true;
    }
};
  

在上面的示例中,IDictionary<VueMutation>接口允许我键入对象vlue的值,但允许任何字符串索引。

1 个答案:

答案 0 :(得分:3)

您可以使用key in construct:

export const enum MutationKeys {
  registerUser = 'registration/REGISTER',
  registerUserCompleted = 'registration/REGISTER_COMPLETED'
}

type MutationDictionnary<P> = {
  [key in MutationKeys]: P
}

const mutations: MutationDictionnary<VuexMutation> = {
  ['registration/REGISTER'](state, payload) {
    state.registration = {
      meta: {
        serverValidated: false
      },
      value: payload
    };
  },
  ['registration/REGISTER_COMPLETED'](state) {
    state.registration.meta.serverValidated = true;
  }
};