Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created July 15, 2020 20:26
Show Gist options
  • Save karol-majewski/b7f46141a84c4a2d8d0dead84a06414e to your computer and use it in GitHub Desktop.
Save karol-majewski/b7f46141a84c4a2d8d0dead84a06414e to your computer and use it in GitHub Desktop.
Turn Map.prototype.has into a type guard
const inventory = new Map([
['🍊', 3],
['🍌', 1],
['🍏', 15],
] as const);
if (inventory.has('🍊')) {
const oranges: number = inventory.get('🍊');
}
declare global {
interface Map<K, V> {
has<T extends K>(key: T): this is { get(key: T): V } & Map<K, V>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment