0

I am getting some typescipt error for the below code, actually for the below interface, items can be object or array based on the code and response, but I am not sure on how to add datatype of array/object/any, more specifically 'any' to the items property

export interface Test {
  items: {
   test1: testing[],
   test2: testing[]
  }
}
2
  • You mean, 'items' can either be an object or an array? Commented Apr 9, 2020 at 7:32
  • @AdilKhalil Yes, you are right, here I am putting it as object but it can be an array Commented Apr 9, 2020 at 7:36

2 Answers 2

1

If you want a property to be able to have multiple types, you can do the following:

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

You can make it more readable by adding more interfaces:

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

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

You can also create this into a reusable and generic Type:

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

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

export interface Test {
  items: Testing<testing>
}

(using lowercase for classes or types is frowned upon though)

Sign up to request clarification or add additional context in comments.

Comments

0

You need to add new interface for every new object

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.