如何使用条件接口或在打字稿中同时使用它们

如何使用条件接口或在打字稿中同时使用它们

本文介绍了如何使用条件接口或在打字稿中同时使用它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 typescript 的新手.在这里,我有两个界面

I am new to the typescript. Here i have two inerfaces

interface TestProduct {
  Id: string
  active: boolean
}

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

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

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

Here , So, I am trying to have both the values like,

type Total = MainProduct | Product

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

Now, When I used this in one of my function methods ,

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.
}
})

因此,如何获得两个接口键值.谢谢.

So, How do I get both intefaces key values over their. thanks.

推荐答案

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

Try to have separate conditional flow for each type.

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 循环中提取通用逻辑,并将其转换为一个单独的函数,并在必要时调用

You can extract common logic from both for loops int a separate function and invoke it if necessary

这篇关于如何使用条件接口或在打字稿中同时使用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:37