Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active May 18, 2021 11:28
Show Gist options
  • Save karol-majewski/c5aeb9c6f2ded29a3bda468572e9a0a9 to your computer and use it in GitHub Desktop.
Save karol-majewski/c5aeb9c6f2ded29a3bda468572e9a0a9 to your computer and use it in GitHub Desktop.
Create an append-only Map in TypeScript
interface Dictionary<K, V> {
forEach(callbackfn: (value: V, key: K, map: Dictionary<K, V>) => void, thisArg?: any): void;
set(key: K, value: V): this;
has<T extends K>(key: T): this is { get(key: T): V } & Dictionary<K, V>;
has(key: K): boolean;
get(key: K): V | undefined;
readonly size: number;
}
interface DictionaryConstructor {
new<K, V>(entries?: readonly (readonly [K, V])[] | null): Dictionary<K, V>;
}
const Dictionary: DictionaryConstructor = Map;
@karol-majewski
Copy link
Author

karol-majewski commented Jul 15, 2020

Usage:

type Fruit = 'orange' | 'apple';

const inventory = new Dictionary<Fruit, number>();

inventory.set('apple', 10);
inventory.set('orange', 20);

inventory.delete('apple'); // Compile-time error
inventory.clear(); // Compile-time error

if (inventory.has('apple')) {
  const count: number = inventory.get('apple');
  
  inventory.set('apple', count + 1);
}

@karol-majewski
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment