无法使用Typescript为属性提供正确的数据类型

时间:2020-04-09 07:29:48

标签: typescript

我在下面的代码中遇到了一些typecipt错误,实际上在下面的接口中,根据代码和响应,项可以是对象或数组,但是我不确定如何添加数组/对象/任何数据类型,更具体地说,是item属性的“ any”

export interface Test {
  items: {
   test1: testing[],
   test2: testing[]
  }
}

2 个答案:

答案 0 :(得分:1)

如果您希望某个属性具有多种类型,则可以执行以下操作:

export interface Test {
  items: { test1: testing[], test2: testing[] } | testing[] | any
}

您可以通过添加更多界面来使其更具可读性:

export interface ItemTesting {
  test1: testing[],
  test2: testing[]
}

export interface Test {
  items: ItemTesting | testing[] | any
}

您还可以将其创建为可重用且通用的Type

export interface ItemTesting<T> {
  test1: T[],
  test2: T[]
}

export type Testing<T> = ItemTesting<T> | T[] | any;

export interface Test {
  items: Testing<testing>
}

(虽然不赞成使用小写的类或类型)

答案 1 :(得分:0)

您需要为每个新对象添加新接口

export interface Test {
  items: Item
}
export interface Item{
   test1: testing[],
   test2: testing[]
}
export interface testing{
   key:value;
}
相关问题