Daniel Santos
Daniel Santos

Reputation: 15828

Typescript native shorthand for value dictionary

I just create a dictionary Interface like:

export default interface IDictionary<T> {
  [key: string]: T;
}

where I'm able to declare variables like

const myDic1 = IDictionary<boolean>;
const myDic2 = IDictionary<number>;

But I would like to know if is there any other (more universal) notation in typescript that describe the same or similiar type of interface.

Or should I import my IDictionary in every project of mine.

Upvotes: 3

Views: 48

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249686

The predefined type Record can be used to obtain an equivalent type.

declare const myDic1: Record<string, boolean>;
declare const myDic2: Record<string, number>;

Record is usually used for more specific keys (ex: Record<"key1" | "key2", boolean>) but it works with string as well.

Upvotes: 2

Related Questions