1

In Typescript I'd like to leverage my string enumeration:

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

so that it's string values provide type-checking constraints on an object like this:

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

In the above example the IDictionary<VueMutation> interface allows me to type the value of the object vlue but allows any string index.

1 Answer 1

4

You can use 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;
  }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.