Created
July 15, 2020 20:26
-
-
Save karol-majewski/b7f46141a84c4a2d8d0dead84a06414e to your computer and use it in GitHub Desktop.
Turn Map.prototype.has into a type guard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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