Skip to content

Instantly share code, notes, and snippets.

@SimGus
Created January 8, 2020 20:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimGus/633a6bc311cdb0e83ca0e3cc54d4f2b8 to your computer and use it in GitHub Desktop.
Save SimGus/633a6bc311cdb0e83ca0e3cc54d4f2b8 to your computer and use it in GitHub Desktop.
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