patterntypescriptCritical
TypeScript hashmap/dictionary interface
Viewed 0 times
typescriptinterfacehashmapdictionary
Problem
I'm trying to implement a hashmap/dictionary interface. So far I have:
I'm having some trouble understanding what exactly this syntax means. If I were to do
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?Solution
Just as a normal js object:
There are two things you're doing with
You can make a general dictionary with explicitly typed fields by using
e.g.
As an alternative, there is a
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.
let myhash: IHash = {};
myhash["somestring"] = "value"; //set
let value = myhash["somestring"]; //getThere 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();
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.
Code Snippets
let myhash: IHash = {};
myhash["somestring"] = "value"; //set
let value = myhash["somestring"]; //getlet map = new Map<object, string>();
let key = new Object();
map.set(key, "value");
map.get(key); // return "value"Context
Stack Overflow Q#42211175, score: 227
Revisions (0)
No revisions yet.