【问题标题】:An index signature parameter type must be either 'string' or 'number'索引签名参数类型必须是“字符串”或“数字”
【发布时间】:2021-10-21 17:41:07
【问题描述】:

我正在使用 typescript 在 React 中构建一个电子商店,其中我有一个 Cart 和一个 CartItem 类,如下所示:

export class CartItem {
  public id: bigint;

  public file: File;

  public constructor(file: File) {
    this.id = file.id;
    this.file = file;
  }
}

export class Cart{
  public items: { [id: bigint]: CartItem };

  public constructor() {
    this.items = {};
  }
}

问题是An index signature parameter type must be either 'string' or 'number' 现在,id 必须是 bigint,它与索引签名参数不兼容。有关如何解决此问题的任何建议?

【问题讨论】:

  • 使用Map 可以有任意键类型

标签: typescript


【解决方案1】:

您可以简单地将您的 bigint 转换为字符串。

或者,您也可以获取 bigint 的哈希值。这将为您的字符串设置一个长度,如果您使用真正的大数字,可能会更好。

如果您需要原始 id,如果您使用哈希方法,只需将其添加到 basketitem 类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 2019-09-13
    • 2020-09-17
    • 2020-05-05
    • 2017-05-06
    • 2019-11-04
    • 2020-05-26
    • 2021-06-02
    相关资源
    最近更新 更多