Skip to content

Instantly share code, notes, and snippets.

@dphilipson
Created February 4, 2017 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dphilipson/4e2ce901cbf237d38a79b554e9d915cb to your computer and use it in GitHub Desktop.
Save dphilipson/4e2ce901cbf237d38a79b554e9d915cb to your computer and use it in GitHub Desktop.
// ----- 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