为什么此代码会产生错误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)
最重要的是,我该如何解决这个问题?
我正在尝试创建一个函数来规范化我的数组,并且期望一个结构如下的输出对象:
{
allIds: [1],
byId: {
1: {...}
}
}
Run Code Online (Sandbox Code Playgroud)
要么
{
allIds: ['1'],
byId: {
'1': {...}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个接口IOutput
来满足此要求。
我已经试过了:
interface IOutput {
allIds: string[] | number[]
byId: {
[key: number | string]: any
}
}
Run Code Online (Sandbox Code Playgroud)
但这给了我以下错误
索引签名参数类型必须为“字符串”或“数字”。ts(1023)
当我这样做时,它似乎起作用:
interface IOutput {
allIds: string[] | number[]
byId: {
[key: number]: any
}
}
Run Code Online (Sandbox Code Playgroud)
要么
interface IOutput {
allIds: string[] | number[]
byId: {
[key: string]: any
}
}
Run Code Online (Sandbox Code Playgroud)
但这不是我想要实现的目标。我也试过了,它给了我同样的错误:
type StringOrNumber = string | number
interface …
Run Code Online (Sandbox Code Playgroud) 我有一个包含符号作为键的对象.在这种情况下如何进行解构分配?
let symbol = Symbol()
let obj = {[symbol]: ''}
let { /* how do I create a variable here, that holds the value of [symbol] property? */ } = obj
Run Code Online (Sandbox Code Playgroud)
我需要知道这是否可能,我确实知道明显而简单的解决方法,但这不是我所要求的.
使用时let s = Symbol()
把该符号声明作为对象的密钥,如:
let a = { [s]:1 }
Run Code Online (Sandbox Code Playgroud)
的类型a
将自动变为,{[x:string]:number}
而尝试索引时会出错a[s]
:
类型“符号”不能用作索引类型 (2538)
而 useconst s = Symbol()
声明是工作 as become to {[s]:number}
。