最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript: How to accept 2 different types - Stack Overflow

programmeradmin7浏览0评论

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 {
      ///
   }
}

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 {
      ///
   }
}
Share Improve this question asked Dec 15, 2021 at 5:31 sal3jfcsal3jfc 7872 gold badges8 silver badges18 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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 {
        ///
    }
}

You can use instanceof:

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

Late to the party!

There's also this method you can use, just found it on another so question:

https://stackoverflow./a/70728314/15832658

I like it because it's clean and you know which type you're referring to

Also you can check other answers of that thread, there are different nice ways to do it

发布评论

评论列表(0)

  1. 暂无评论