Typescript Dictionary
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... |
This comment has been minimized.
This comment has been minimized.
Hi, I get this: Typescript 3.0.1 |
This comment has been minimized.
This comment has been minimized.
Hi, I get the following: Line 30: let v = this.dict[key] as V; Line 38: return this.dict[key] as V; Line 42: this.dict[key] = val; My tsconfig:
My package dependencies:
|
This comment has been minimized.
This comment has been minimized.
Maybe I should just use mapped types directly - rewrite incoming |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
The latest revision works with strict mode in the typescript compiler