打字稿:使用符号作为键破坏对象

时间:2019-01-02 10:16:11

标签: typescript destructuring

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

最重要的是,我该如何解决?

1 个答案:

答案 0 :(得分:1)

您只需要将symbol声明为const,以使编译器为其推断类型,而不是一般的Symbol类型。

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


console.log(alias)

当打字稿推断出唯一符号时,此PR可能很有用