chaya D
chaya D

Reputation: 151

create generic class to hold key value array (dictionary) with typescript

i want to add Dictionary class for using in my app. i created a class, and added an Array of keyValuePair to it, to hold my list

export class KeyValuePair<TKey, TVal>{
key:TKey;
value:TVal;

constructor(key:TKey, val:TVal){
    this.key = key;
    this.value = val;
}

export class Dictionary<TKey, TVal>{
    array: Array<KeyValuePair<TKey, TVal>>
}

let myClassInstance:Dictionary<number, string> = ...;

questions:

  1. i want to be able to iterate it with forEach or in a loop as let x of myClassInstance how can i do this? (myClassInstance.forEach(...);)
  2. can i use the class instance to get my array without calling className.arrayName?(myClassInstance.find(...);)
  3. can I use the class instance as an index to get the values?(myClassInstance[1])

Upvotes: 0

Views: 677

Answers (1)

devdgehog
devdgehog

Reputation: 625

Have a look at Map, they are dictionaries.

You can use them like this: Playground.

You can iterate their values, keys or entries and they will be typed. You can find something using get. You can convert them to arrays [...myMap.values()], note: they will be ordered by the key insertion order. (you can use entries() instead and then map the result to sort by keys if needed)

Upvotes: 1

Related Questions