如何使用条件接口或在typescript中同时使用它们

IT技术 angularjs reactjs typescript
2021-05-25 13:48:50

我是新来的typescript这里我有两个接口

interface TestProduct {
  Id: string
  active: boolean
}

interface Product {
  Id?: string
  Name?: string
  Original: TestProduct
}

interface MainProduct {
  Id?: string
  Name?: string
  Original?: Product
}

在这里,所以,我试图同时拥有这两个值,

type Total = MainProduct | Product

现在,当我在我的一个函数方法中使用它时,

getproducts = memoize(
    (products: Array<Product>, isopen) => {
    //did some group by and got one array of object.

   const groupedValues = !isopen  ?  _.groupBy(
    products,
    (bsp: Product) => bsp?.Original?.active?.Name ?? 'Undefined'
  ) :  _.groupBy(
    buyingSessionProducts,
    (bsp: MainProduct) => bsp?.Original?.Original?.active?.Name ?? 'Undefined'
  )


   for (let value in groupedValues) {
    const sort = groupedValues[value][0].original?. //here I am able to get only Id value as it is common in both the interface. So, I am not getting either original?.active or direct original?.original?.active.
}
})

那么,我如何获得两个接口的关键值。谢谢。

1个回答

尝试为每种类型设置单独的条件流。

getproducts = memoize(
(products: Array<Product>, isopen) => {
  //did some group by and got one array of object.

  if(!isopen) {
      const groupedProductValues = _.groupBy(
        products,
        (bsp: Product) => bsp?.Original?.active?.Name ?? 'Undefined'
      )

      for (let value in groupedValues) {
          // Here value is of type Product
      }
  } else {
      const groupedMainProductValues = _.groupBy(
          buyingSessionProducts,
          (bsp: MainProduct) => bsp?.Original?.Original?.active?.Name ?? 'Undefined'
      )

      for (let value in groupedValues) {
          // Here value is of type MainProduct
      }
  }
})

您可以在for一个单独的函数中从两个循环中提取公共逻辑,并在必要时调用它