Typescript: destructuring an object with symbols as keys

爱⌒轻易说出口 提交于 2019-12-10 16:49:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!