HomeToolsAbout a20k

Object Strategies

Typing Object

Source

// dictionary = any number of properties of the same type interface StringDictionary { [key: string]: string; } const obj: StringDictionary = { key1: "value-1", key2: "value-2", keyn: "value-n" }; // record = equivalent to dictionary above const obj: Record<string, string> = { key1: "value-1", key2: "value-2", keyn: "value-n", }; // enums enum KeysEnum { FIRST = "firstKey", SECOND = "secondKey", } type EnumDictionary = Record<KeysEnum, string>; const obj: EnumDictionary = { [KeysEnum.FIRST]: "value1", [KeysEnum.SECOND]: "value2", };

Typing Index Key

Without explicit declaration of key as index, the key passed to an object via object[key] will result in type error

const allTypes = { "thisthing": "", "anotherthing": "", "something": "find this", }; const lookUpKey = "something"; const valueToLookFor = allTypes[lookUpKey as keyof typeof allTypes]

Combining Static and Dynamic Keys

interface MixedDictionary { // static staticKey: string; // dynamic = dictionary [key: string]: string | number; } const obj: MixedDictionary = { staticKey: "staticValue", dynamicKey1: "value-1", dynamicKey2: "value-2", dynamicKeyn: "value-n", };
© VincentVanKoh