Skip to content

Instantly share code, notes, and snippets.

@SimGus
Created Jan 8, 2020
Embed
What would you like to do?
Maps (dicts) in TypeScript
// When programming, there will certainly be times you will want to associate values to other values,
// that is building a dictionary.
// In TypeScript, a `Map<K, V>` exists (it seems it actually is the one defined in JavaScript ES6).
// However, at least in TypeScript 3.1.6, objects from this class are not very reliable:
// You will sometimes get errors such as "TypeError: map.get is not a function", at seemingly random times.
// A solution is to replace `Map<string, V>` by plain objects defined as `{ [key: string]: V }`.
// Another solution seems to be to replace them by `Record<string, V>`.
// This gist presents the first solution.
function unreliableWithMap(): void {
let map: Map<string, string[]> = new Map();
// Put a new value in the dict
map.set('key', ['value1', 'value2']);
// Remove a value
map.delete('key');
// Get a value
const value: string[] = map.get('key');
// Looping over entries
for (const [key, value] of map.entries) {
console.log(key, '=>', value);
}
}
function reliableWithObjects(): void {
let map: { [key: string]: string[] } = {};
// Put a new value in the dict
map['key'] = ['value1', 'value2'];
// Remove a value
delete map['key'];
// Get a value
const value: string[] = map['key'];
// Looping over entries
for (const [key, value] of Object.entries(map)) {
console.log(key, '=>', value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment