Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: How to accept 2 different types

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 {
      ///
   }
}
like image 431
sal3jfc Avatar asked May 12 '26 12:05

sal3jfc


1 Answers

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
   }
}
like image 85
LovingGarlic Avatar answered May 14 '26 02:05

LovingGarlic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!