Search code examples
javascripttypescripttypesinterface

What is the best way to use union or extend when I have a similar context in typescript?


So I have a function that receives 2 types of objects, something like this:

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"])

My interfaces:

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

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

Context: We have 2 similar interfaces because we have 1 default page (in production) and another generic page that's still in development. We didn't want to touch or change the structure of the default page, so we're just trying to share the submit handlers of both pages in this case to avoid the duplication of the service/button handlers.

The question is: Is is correct to declare that way every time I call a function inside of the submitHandler or do we have another easier way to type that?

In this context, if I add a new type like:

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

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

and start to receive both objects

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

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


Can I just create another interface and extend to GenericAllTheDatas? is that a good practice?


Solution

  • Try using a type instead of an interface until that interface is different. Note that under the hood interfaces and types are the same.

    type GenericAllTheDatas = AllTheDatas;