Typescript Indexable Types | Concept

Ole Ersoy
Feb - 22  -  1 min

Typescript and Javascript support indexing by number as in arrays and by string as in associative arrays or Object ( {} ) instances.

Typescript Indexable Types allow us to be explicit about the key signature.

Examples

Associate Array

interface KeyBoolean {
    [key: string]: boolean
}

Objects implementing this interface will have a key of type string and the values will be of type boolean.

let kv: KeyBoolean = {'FOCUSED': true, 'BLURRED':false};
console.log(kv); // { FOCUSED: true, FOCUSED: false }

For maximum flexibility with respect to values keyed use any as the type:

interface KeyAny {
    [key: string]: any
}


let ka:KeyAny = {};
ka.dateOfBirth = new Date(0);
ka.firstName = 'Mozart';

Function Signature

This function takes a peopleObject argument that maps a person string ID to the person:

function objectArgument(peopleObject: { [key: string]: Person })

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'];

For positional indexers we can include additional properties that are part of the array prototype:

interface Elements {
    [index: number]: string;
    length: number;
    push(): number;
    pop(): string;
}