typescriptindex-signature

Index signature where key is string vs [string]


What's the difference between these two?

let foo:{ [index:string] : string } = {
    ['hello']: 'world'
};

let bar:{ [index:string] : string } = {
    'hello': 'world'
};

I get the same result (world) when for the two values

console.log(foo['hello'])
console.log(bar['hello'])

Solution

  • The first one allows to pass a variable between the square brackets:

    const key = 'hello';
    
    let foo:{ [index:string] : string } = {
        [key]: 'world'
    };
    

    But in your current example you're passing a plain string so you are using the dynamic syntax with a static key. ['hello']: 'world' is fully equivalent to 'hello': 'world'.