Le Dinh Nhat Khanh Le Dinh Nhat Khanh - 26 days ago 8
TypeScript Question

What does this code mean in typescript?

interface Options {
[key: string]: any;
}


It's quite complicate to me, 'key' has type string and any?

Thank you.

Answer

It means objects that implement the Options interface are indexable. The indexable key is of type string, and can return any.

From https://www.typescriptlang.org/docs/handbook/interfaces.html:

Indexable Types

We can describe types that we can “index into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

Example:

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];
Comments