Typescript: How to accept 2 different types

Viewed 98

I have a method getRoute that takes a video. The video is either of LiveVideo type or RecordedVideo type. My problem is that getLiveID field is only in LiveVideo so I am getting the editor issue property getLiveID does not exist on type RecordedVideo. What is the way around this? I want to use 1 method to handle both and handle the conditional logic within.

getRoute(video: LiveVideo | RecordedVideo) {
   if (video.getLiveID) {

     ///
   } else {
      ///
   }
}
3 Answers

You can use instanceof:

getRoute(video: LiveVideo | RecordedVideo) {
  if (video instanceof LiveVideo) {
    // "video" is of type LiveVideo here...
  } else {
    // ...
  }
}

You can check which type you have using in. For example:

getRoute(video: LiveVideo | RecordedVideo) {
   if ("getLiveId" in video) {
     // treat as LiveVideo
   } else {
     // as RecordedVideo
   }
}
type LiveVideo = {
    getLiveID: Function,
    id: string
}

type RecordedVideo = {
    id: string
}

function getRoute(video: LiveVideo | RecordedVideo) {
    if ((video as LiveVideo)?.getLiveID) {

        ///
    } else {
        ///
    }
}
Related