close

[Solved] An index signature parameter type cannot be a union type. Consider using a mapped object type instead

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error An index signature parameter type cannot be a union type. Consider using a mapped object type instead in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How To Solve An index signature parameter type cannot be a union type. Consider using a mapped object type instead Error ?

  1. How To Solve An index signature parameter type cannot be a union type. Consider using a mapped object type instead Error?

    To Solve An index signature parameter type cannot be a union type. Consider using a mapped object type instead Error The simplest solution is to use Record

  2. An index signature parameter type cannot be a union type. Consider using a mapped object type instead

    To Solve An index signature parameter type cannot be a union type. Consider using a mapped object type instead Error The simplest solution is to use Record

Solution 1

You can use TS “in” operator and do this:

enum Options {
  ONE = 'one',
  TWO = 'two',
  THREE = 'three',
}
interface OptionRequirement {
  someBool: boolean;
  someString: string;
}
type OptionRequirements = {
  [key in Options]: OptionRequirement; // Note that "key in".
}

Solution 2

The simplest solution is to use Record

type OptionRequirements = Record<Options, OptionRequirement>

You can also implement it yourself as:

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

This construct is only available to type, but not interface. The problem is your definition is saying the key of your interface should be of type Options, where Options is an enum, not a string, number, or symbol. The key in Options means “for those specific keys that are in the union type Options”.

type alias is more flexible and powerful than interface. If your type does not need to be used in class, choose type over interface.

Solution 3

I had some similar problems but my case was with another field property in the interface so my solution is an example with optional field property with an enum for keys:

export enum ACTION_INSTANCE_KEY {
  cat = 'cat',
  dog = 'dog',
  cow = 'cow',
  book = 'book'
}

type ActionInstances = {
  [key in ACTION_INSTANCE_KEY]?: number; // cat id/dog id/cow id/ etc // <== optional
};

export interface EventAnalyticsAction extends ActionInstances { // <== need to be extended
  marker: EVENT_ANALYTIC_ACTION_TYPE; // <== if you wanna add another field to interface
}

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment