Convenient type definitions for commonly used dictionary/map style objects in TypeScript.
Since TypeScript 2.1, TypeScript has a built-in Record type which renders
this package obsolete. Consider also using an ES6 Map instead.
- Instead of
Dictionary<T>, useRecord<string, T>orMap<string, T>. - Instead of
Dictionary<T, K>, useRecord<K, T>orMap<K, T>. - Instead of
ReadonlyDictionary<T>, useReadonly<Record<string, T>>orReadonlyMap<string, T>. - Instead of
ReadonlyDictionary<T, K>, useReadonly<Record<K, T>>orReadonlyMap<K, T>. - Instead of
NumberMap<T>, useRecord<number, T>orMap<number, T>. - Instead of
ReadonlyNumberMap<T>, useReadonly<Record<number, T>>orReadonlyMap<number, T>.
npm install --save dictionary-typesimport {
Dictionary,
ReadonlyDictionary,
NumberMap,
ReadonlyNumberMap
} from "dictionary-types";An object containing elements of type T, keyed by string.
const scores: Dictionary<number> = {
"Amelia": 4,
"Riley": 7,
"April": 5
};
scores["Xander"] = 3;An object containing elements of type TValue, keyed by TKey.
const amelia = Symbol();
const riley = Symbol();
const april = Symbol();
const xander = Symbol();
type Participant = typeof amelia | typeof riley | typeof april | typeof xander;
const scores: Dictionary<number, Participant> = {
[amelia]: 4,
[riley]: 7,
[april]: 5
};
scores[xander] = 3;A read-only object containing elements of type T, keyed by string.
function winner(scores: ReadonlyDictionary<number>): string {
let winner = "";
let highScore = 0;
for (const name of Object.keys(scores)) {
if (scores[name] > highScore) {
highScore = scores[name];
winner = name;
}
}
return name;
}A read-only object containing elements of type TValue, keyed by TKey.
const amelia = Symbol();
const riley = Symbol();
const april = Symbol();
const xander = Symbol();
type Participant = typeof amelia | typeof riley | typeof april | typeof xander;
function winner(scores: ReadonlyDictionary<number, Participant>): Participant | null {
let winner: Participant | null = null;
let highScore = 0;
for (const participant of [amelia, riley, april, xander]) {
if (scores[participant] > highScore) {
highScore = scores[participant];
winner = participant;
}
}
return winner;
}An object containing elements of type T, keyed by number.
A read-only object containing elements of type T, keyed by number.
See LICENSE.md.