Last active
September 28, 2018 02:19
-
-
Save snewell92/de233fbe11a5e4b159da1cf8e8f1b766 to your computer and use it in GitHub Desktop.
Typescript Dictionary
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
type KEY = string | number | symbol; | |
interface Dictionary<K extends KEY, V> { | |
getKeys(): K[]; | |
getValues(): V[]; | |
get(key: K): V | null; | |
put(key: K, val: V): void; // or boolean? | |
} | |
class JSDict<K extends KEY, V> implements Dictionary<K, V> { | |
private dict: { [key in K]?: V }; | |
constructor() { | |
this.dict = {}; | |
} | |
public getKeys() { | |
let keys: K[] = []; | |
for(let key in this.dict) { | |
keys.push(key); | |
} | |
return keys; | |
} | |
public getValues() { | |
let vals: V[] = []; | |
for (let key in this.dict) { | |
let v = this.dict[key]; | |
if (this.exists(v)) { | |
vals.push(v); | |
} | |
} | |
return vals; | |
} | |
// Type predicate to ensure v exists | |
private exists(v: V | undefined): v is V { | |
return v != null && typeof v !== "undefined"; | |
} | |
public get(key: K) { | |
let v = this.dict[key]; | |
return this.exists(v) | |
? v | |
: null; | |
} | |
public put(key: K, val: V) { | |
this.dict[key] = val; | |
} | |
static Create<Keys extends KEY, Values>() { | |
return new JSDict<Keys, Values>(); | |
} | |
} | |
type Fruits = "Apples" | "Bananas" | "Oranges"; | |
var d = JSDict.Create<Fruits, number>(); | |
d.put("Bananas", 5); | |
// etc... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe I should just use mapped types directly - rewrite incoming