6

Why this code produces an error Type 'symbol' cannot be used to index type '{ [x: string]: string; }'.:

let symbol = Symbol()
let obj = { [symbol] : 'value'}
let { [symbol]: alias } = obj
             // ^^^^^ the error is here

console.log(alias)

And most importantly, how do I fix this?

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89

1 Answers1

2

You just need to declare the symbol as const to make the compiler infer a literal type for it and not the general Symbol type.

const symbol = Symbol()
let obj = { [symbol] : 'value'}
let { [symbol]: alias } = obj


console.log(alias)

This PR might be useful as to when typescript infers a unique symbol

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357