打字稿:使用符号作为键破坏对象 [英] Typescript: destructuring an object with symbols as keys

查看:46
本文介绍了打字稿:使用符号作为键破坏对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码会产生错误类型'symbol'不能用于索引类型'{[x:string]:string;}'.:

 让symbol = Symbol()让obj = {[symbol]:'value'}让{[符号]:别名} = obj//^^^^^错误在这里console.log(别名) 

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

解决方案

您只需要将符号声明为 const ,以使编译器为其推断文字类型而不是一般的 Symbol 类型.

  const符号= Symbol()让obj = {[symbol]:'value'}让{[符号]:别名} = objconsole.log(别名) 

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

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?

解决方案

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

这篇关于打字稿:使用符号作为键破坏对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆