繁体   English   中英

Typescript接口类型,可选不同类型的按键

[英]Typescript interface type with optional keys of different types

这是我通过 API 收到的数据。

i_1: {count: 1, name: 'name1', price: 35000}
i_2: {count: 1, name: 'name2', price: 30000}
i_3: {count: 1, name: 'nam3', price: 30000}

我这样定义它的类型。

interface Item {
  count: number;
  name: String;
  price: number;
}

我将其添加到名为 Data 的类型属性中。

interface Data {
  items?: Item;
 ...etc
}

但是当我尝试使用 Object.entries 时遇到了问题。

代码

Object.entries(items).map(([key, value]) => ())

错误信息是:

No overload matches this call.
  Overload 1 of 2, '(o: { [s: string]: unknown; } | ArrayLike<unknown>): [string, unknown][]', gave the following error.
    Argument of type 'Item | undefined' is not assignable to parameter of type '{ [s: string]: unknown; } | ArrayLike<unknown>'.
      Type 'undefined'enter code here is not assignable`enter code here` to type '{ [s: string]: unknown; } | ArrayLike<unknown>'.
  Overload 2 of 2, '(o: {}): [string, any][]', gave the following error.
    Argument of type 'Item | undefined' is not assignable to parameter of type '{}'.
      Type 'undefined' is not assignable to type '{}'.

任何帮助,将不胜感激。

您正在将可能未定义的类型传递给Object.entries ,要解决此问题,您可以使用 nullish 合并运算符:

Object.entries(items ?? {}).map(([key, value]) => ())

此外, TypeScript 为Object.entries提供了一个泛型类型,因此如果您想让它使用更精确的类型,您可以使用强制转换或参考Typescript Key-Value relation preserving Object.entries 类型的解决方案,使您的自己的Entries<T>类型为Object.entries

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM