Created
February 4, 2017 00:33
-
-
Save dphilipson/4e2ce901cbf237d38a79b554e9d915cb to your computer and use it in GitHub Desktop.
This file contains 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
// ----- Definition ----- | |
class SafeMap<V> { | |
private readonly o: { [key: string]: V } = {}; | |
public put(key: string, value: V): void { | |
this.o[key] = value; | |
} | |
public has<K extends string>(key: K): this is SafeMapWithKey<K, V> { | |
return key in this.o; | |
} | |
private get(key: string): V { | |
return this.o[key]; | |
} | |
} | |
interface SafeMapWithKey<K extends string, V> { | |
get(key: K): V; | |
} | |
// ----- Usage ----- | |
const map = new SafeMap<number>(); | |
// TypeScript error: Property 'get' is private. | |
console.log(map.get("hello")); | |
// Typechecks fine. | |
if (map.has("hello")) { | |
console.log(map.get("hello")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment