TypeScript hashmap/dictionary interface
I'm new to using TypeScript and I'm trying to implement a hashmap/dictionary interface. So far I have
export interface IHash {
[details: string] : string;
}
I'm having some trouble understanding what exactly this syntax means. If I were to do var x : IHash = {};
how would I go about adding/accessing the data?
Just as a normal js object:
let myhash: IHash = {};
myhash["somestring"] = "value"; //set
let value = myhash["somestring"]; //get
There are two things you're doing with [indexer: string] : string
- tell TypeScript that the object can have any string-based key
- that for all key entries the value MUST be a string type.
You can make a general dictionary with explicitly typed fields by using [key: string]: any;
e.g. age
must be number
, while name
must be a string - both are required. Any implicit field can be any type of value.
As an alternative, there is a Map
class:
let map = new Map<object, string>();
let key = new Object();
map.set(key, "value");
map.get(key); // return "value"
This allows you have any Object instance (not just number/string) as the key.
Although its relatively new so you may have to polyfill it if you target old systems.
The most simple and the correct way is to use Record type Record<string, string>
const myVar : Record<string, string> = {
key1: 'val1',
key2: 'val2',
}
var x : IHash = {};
x['key1'] = 'value1';
x['key2'] = 'value2';
console.log(x['key1']);
// outputs value1
console.log(x['key2']);
// outputs value2
If you would like to then iterate through your dictionary, you can use.
Object.keys(x).forEach((key) => {console.log(x[key])});
Object.keys returns all the properties of an object, so it works nicely for returning all the values from dictionary styled objects.
You also mentioned a hashmap in your question, the above definition is for a dictionary style interface. Therefore the keys will be unique, but the values will not.
You could use it like a hashset by just assigning the same value to the key and its value.
if you wanted the keys to be unique and with potentially different values, then you just have to check if the key exists on the object before adding to it.
var valueToAdd = 'one';
if(!x[valueToAdd])
x[valueToAdd] = valueToAdd;
or you could build your own class to act as a hashset of sorts.
Class HashSet{
private var keys: IHash = {};
private var values: string[] = [];
public Add(key: string){
if(!keys[key]){
values.push(key);
keys[key] = key;
}
}
public GetValues(){
// slicing the array will return it by value so users cannot accidentally
// start playing around with your array
return values.slice();
}
}