Search code examples
typescript

What does this type declaration mean in Typescript?


I'm new to Typescript and I'm reading over someone else's code and having trouble with this declaration:

    private somevar: { [s: string]: string };

What type is this? Square brackets indicate an array, but I'm confused about exactly what shape this would be in.


Solution

  • It's an indexable type. Looking at this variable definition's type expression:

    let myIndexVar: { [key: string]: number; };
    
    • : { ... } means it's an object.
    • [key: string]: number; is the index signature of the object.

    Within the index signature:

    • [key: string] defines the name of the key—key—and the type of the key—string.
    • : number; is the type of the value—number.

    These types are used like so:

    let myIndexVar: { [key: string]: number; } = {};
    
    myIndexVar["key"] = 4; // key is string, value is number
    

    Note that you can give the key any name you like. Giving it a descriptive name is helpful to tell what the key is, though the variable name should also do that:

    Intellisense example