【问题标题】:Mixing dynamic and static object keys in type or interface在类型或接口中混合动态和静态对象键
【发布时间】:2021-01-12 08:04:23
【问题描述】:

我需要这样的东西:

interface IMyInterface {
    Payload?: object;
    [key: string]: boolean | string | number | Date;
}

但上面的代码给了我以下错误

“对象”类型的属性“有效负载”| undefined' 不能分配给字符串索引类型'string |号码 |布尔值 |日期”。

有没有办法通过interfacetype 实现我想要的类型?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    在您的示例中:IMyInterface 定义中的第二行:[key: string]: boolean | string | number | Date; 表示所有字段的类型均为boolean | string | number | Date

    您可以通过使用联合类型来定义:

    type MyType =
        {[key : string]: boolean | string | number | Date} & { Payload?: object}
    

    【讨论】:

      猜你喜欢
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多