简体   繁体   中英

Creating an array from condition

i need to create an array, but the object type is different depending on a condition, something like this:

  myList = condition()
      ? Array < { secondLabel: String, value: String } > []
      : Array < { label: String, value: Number } > []

but, Im getting these errors:

Cannot compare class Array [1] to object literal [2].

Cannot compare boolean [1] to empty array literal [2].

Just use the array constructor !

const myList = true ?
  new Array<{ secondLabel: String, value: String }>()
  : new Array<{ label: String, value: Number }>()

or you can asert the type:

const myList = condition()
  ? [] as Array<{ secondLabel: String, value: String }>
  : [] as Array<{ label: String, value: Number }>

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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