问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/54004512/typescript-destructuring-an-object-with-symbols-as-keys