jarora
jarora

Reputation: 5762

Creating a Generic Dictionary in Typescript

I am trying to create a Generic type that represents a dictionary. Something like this:

export type Dictionary<K extends string | number, V> = {[k: K]: V};

Even though I've limited the type to string | number, I still get an error saying "An index signature parameter type must be either 'string' or 'number'.". Is there any way to achieve this in Typescript?

Upvotes: 0

Views: 80

Answers (1)

OliverRadini
OliverRadini

Reputation: 6467

Record is handy for these kind of situations:

export type Dictionary<K extends string | number, V> = Record<K, V>;

Upvotes: 1

Related Questions