相关疑难解决方法(0)

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

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

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

destructuring typescript

6
推荐指数
1
解决办法
615
查看次数

TypeScript:尝试使用字符串|时,索引签名参数必须为“字符串”或“数字” 数

我正在尝试创建一个函数来规范化我的数组,并且期望一个结构如下的输出对象:

{
  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)

interface normalization typescript

5
推荐指数
2
解决办法
1167
查看次数

ES6:使用符号作为键来解构对象

我有一个包含符号作为键的对象.在这种情况下如何进行解构分配?

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)

我需要知道这是否可能,我确实知道明显而简单的解决方法,但这不是我所要求的.

UPD.有趣的是我知道怎么做但是打字稿产生错误,我认为我在JS中做错了.这是打字稿用户的修复程序.

javascript destructuring ecmascript-6

3
推荐指数
1
解决办法
213
查看次数

为什么“让”声明符号会转换为 TypeScript 中的字符串索引签名?

使用时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}

typescript typescript-typings

0
推荐指数
1
解决办法
54
查看次数