打字稿:以符号为键解构对象

Typescript: destructuring an object with symbols as keys

为什么这段代码会产生错误 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)

最重要的是,我该如何解决这个问题?

您只需将 symbol 声明为 const 即可让编译器为其推断文字类型,而不是一般的 Symbol 类型。

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


console.log(alias)

这个 PR 可能对打字稿何时推断出唯一符号有用