Typescript Indexable Types

Photo by jesse orrico on Unsplash

Updated Version

Scenario

Answer

Examples

Associate Array

interface KeyBoolean {
[key: string]: boolean
}
let kv: KeyBoolean = {'FOCUSED': true, 'BLURRED':false};
console.log(kv); // { FOCUSED: true, FOCUSED: false }
interface KeyAny {
[key: string]: any
}
let ka:KeyAny = {};
ka.dateOfBirth = new Date(0);
ka.firstName = 'Mozart';

Positional Indexer

interface Elements {
[key:number]: string;
}
let e:Elements = ['Hydrogen', 'Helium', 'Lithium'];
console.log(e); //['Hydrogen', 'Helium', 'Lithium']
console.log(e[0]; //Hydrogen
//This is the same as declaring:
let e:string[] = ['Hydrogen', 'Helium', 'Lithium'];
interface Elements {
[index: number]: string;
length: number;
push(): number;
pop(): string;
}

Founder of Firefly Semantics Corporation