Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript An index signature parameter type must be either 'string' or 'number'

Tags:

typescript

I have a generic which its default type is a string:

interface EntityState<typeOfID = string> {
  entities: { [ id: typeOfID]: any };
}

I get the error:

An index signature parameter type must be either 'string' or 'number'.(1023)

I also tried the following:

interface EntityState<typeOfID extends string | number> {
  entities: { [ id: typeOfID]: any };
}

And it doesn't work. How to solve it?

like image 340
undefined Avatar asked Dec 21 '25 18:12

undefined


1 Answers

You can use Record in such a case.

Consider this:

export const enum MyEnumKeys {
  Key1 = 'key1',
}

interface EntityState<typeOfID> {
  entities: Record<typeOfID, any>;
}

const test: EntityState<MyEnumKeys> = {
  entities: {
    key1: 1,
    anotherKey: 2 // error here
  }
}

like image 103
Steve Avatar answered Dec 24 '25 08:12

Steve