Categories
TypeScript Answers

How to fix the ‘An index signature parameter type cannot be a union type. Consider using a mapped object type instead’ error in TypeScript?

Spread the love

Sometimes, we want to fix the ‘An index signature parameter type cannot be a union type. Consider using a mapped object type instead’ error in TypeScript.

In this article, we’ll look at how to fix the ‘An index signature parameter type cannot be a union type. Consider using a mapped object type instead’ error in TypeScript.

How to fix the ‘An index signature parameter type cannot be a union type. Consider using a mapped object type instead’ error in TypeScript?

To fix the ‘An index signature parameter type cannot be a union type. Consider using a mapped object type instead’ error in TypeScript, we should use the in operator to specify the data type of our dynamic keys in our type.

For instance, we write

enum Options {
  ONE = "one",
  TWO = "two",
  THREE = "three",
}

interface OptionRequirement {
  someBool: boolean;
  someString: string;
}

type OptionRequirements = {
  [key in Options]: OptionRequirement;
};

to add the OptionRequirements with the type of the object keys set to key in Options.

This way, the keys should only be the ones listed in Options.

Conclusion

To fix the ‘An index signature parameter type cannot be a union type. Consider using a mapped object type instead’ error in TypeScript, we should use the in operator to specify the data type of our dynamic keys in our type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *