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

Nur*_*yev 6 destructuring typescript

为什么此代码会产生错误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)
Run Code Online (Sandbox Code Playgroud)

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

Tit*_*mir 2

您只需声明symbolasconst即可使编译器推断出它的文字类型而不是通用Symbol类型。

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


console.log(alias)
Run Code Online (Sandbox Code Playgroud)

对于打字稿何时推断唯一符号,此PR可能有用

  • @NurbolAlpysbayev 通常 `let x = litreral` 将推断扩展类型,而 `const x =literal` 将推断文字类型。所以 `let x = 'foo'` x 是 `string` 而 `const x = 'foo'` x 的类型是 `'foo'` (2认同)