Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this dictionary or hashtable in Typescript?

Tags:

typescript

The following code is from ngrx example.

What this declaration will do? Is this equivalent to dictionary or hashtable in C#?

let typeCache: { [label: string]: boolean } = {};

The original code:

let typeCache: { [label: string]: boolean } = {};

export function type<T>(label: T | ''): T {
  if (typeCache[<string>label]) {
    throw new Error(`Action type "${label}" is not unique"`);
  }

  typeCache[<string>label] = true;

  return <T>label;
}
like image 476
wonderful world Avatar asked Jun 10 '26 07:06

wonderful world


1 Answers

I'm not sure about the C# equivalence, but what it means in typescript is a regular javascript object with boolean properties, and it's referred as Indexable Types.
The keys can only be strings or numbers, this won't compile:

let typeCache: { [label: Date]: boolean } = {}; // error: An index signature parameter type must be 'string' or 'number'

Examples of how a value would look like:

type Indexable = { [label: string]: boolean };

let typeCache1: Indexable = { a: true, b: false };
let typeCache2: Indexable = { a: true, b: "string" }; // error: Type '{ a: true; b: "string"; }' is not assignable to type 'Indexable'
like image 154
Nitzan Tomer Avatar answered Jun 11 '26 20:06

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!