0

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'])
McLovin
  • 3,295
  • 7
  • 32
  • 67
  • 2
    As you're seeing, there's no difference. This is not TypeScript, even, it's a computed property name: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015. For key values that are valid identifiers the quotes aren't needed either, `{ hello: "world" }` would work just the same. – jonrsharpe Dec 12 '21 at 11:54

1 Answers1

0

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'.

Guerric P
  • 30,447
  • 6
  • 48
  • 86