【问题标题】:Typescript Inteface where "id" must be number and other properties must be stringTypescript 接口,其中“id”必须是数字,其他属性必须是字符串
【发布时间】:2020-04-26 03:29:35
【问题描述】:

我需要为来自服务器的数据定义一个接口,其中id 是一个数字,但所有其他属性都是字符串。

我试过了:

interface AnyChartsData {
  id: number;
  [key: string]: string;
}

但我收到了这个错误:

[ts] 类型“number”的属性“id”不可分配给字符串索引类型“string”。 [2411]

如何正确定义这个接口?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你必须使用联合类型,因为id 是一个数字而不是一个字符串,例如

    interface AnyChartsData {
        id: number;
        [key: string]: string | number;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多