当我在typescript中有类似的上下文时,使用union或extend的最佳方式是什么?

uidvcgyl  于 2023-01-03  发布在  TypeScript
关注(0)|答案(1)|浏览(76)

所以我有一个函数可以接收两种类型的对象,如下所示:

const canBeGenericOrDefaultData = {
  id: 123,
  pointData: {
  square: 'x145',
  triangle: 'y145'
  }
}

function submitHandler(canBeGenericOrDefaultData: AllTheDatas | GenericAllTheDatas):
  buildPointData(canBeGenericOrDefaultData.pointData)
  // do something
function buildPointData(pointData: AllTheDatas["pointData"] | GenericAllTheDatas["pointData"])

我的界面:

interface AllTheDatas{
 id: string
 pointData: {
  square: string
  triangle: string
 }
}

interface GenericAllTheDatas{
 id: string
 pointData: {
  square: string
  triangle: string
 }
}

上下文:我们有两个相似的界面,因为我们有一个默认页面(在生产中)和另一个仍在开发中的通用页面。我们不想触及或更改默认页面的结构,所以我们只是尝试共享两个页面的提交处理程序,以避免服务/按钮处理程序的重复。
问题是:每次调用submitHandler中的函数时都这样声明是正确的吗?或者我们有其他更简单的方法来输入它吗?
在这个上下文中,如果我添加一个新类型,如:

interface AllTheDatas{
 id: string
 pointData: {
  square: string
  triangle: string
  newForm: string
 }
}

interface GenericAllTheDatas{
 id: string
 pointData: {
  square: string
  triangle: string
 }
}

并开始接收两个对象

const defaultData = {
  id: 123,
  pointData: {
  square: 'x145',
  triangle: 'y145',
  newForm: 'x1234'
  }
}

const genericData = { 
  id: 123,
  pointData: {
  square: 'x145',
  triangle: 'y145'
  }
}

我可以创建另一个接口并扩展到GenericAllTheDatas吗?这是一个好的实践吗?

zbsbpyhn

zbsbpyhn1#

尝试使用类型而不是接口,直到接口不同为止。注意,在底层接口和类型是相同的。

type GenericAllTheDatas = AllTheDatas;

相关问题