【问题标题】:Filtering TypeScript array with two types to just one type将具有两种类型的 TypeScript 数组过滤为仅一种类型
【发布时间】:2018-04-20 13:50:32
【问题描述】:

我正在尝试使用 snoowrap Reddit API wrapper 从 subreddit 中获取报告的评论对象列表。 getReports 方法返回一个 Submission | Comment 类型的数组,但您可以向其中传递一个参数以仅获取返回数据中的 Comments。

但是它仍然作为具有两种类型的数组返回,因此我想使用过滤器来仅保留 Comment 类型的数组。这只会修改项目,不会将数组的类型更改为只是 Comments。

这是我正在尝试的:

getReportedComments(): Comment[] {
    return this.r
        .getSubreddit("subreddit")
        .getReports({ only: "comments" }) // returns a Listing<Submission|Comment>, which is just a subclass of Array
        .filter(comment => comment instanceof Comment)
}

r 是一个 Snoowrap 对象。

有什么建议吗?谢谢。

【问题讨论】:

  • 当您说它“仍然作为具有两种类型的数组返回”时,您的意思是返回类型仍然包含两种类型,还是在运行时请求实际上返回填充了两种类型?

标签: typescript


【解决方案1】:

如果你已经知道只有 cmets,你可以将它转换成你想要的类型。

getReportedComments(): Comment[] {
    return this.r
        .getSubreddit("subreddit")
        .getReports({ only: "comments" }) as Comment[];
}

【讨论】:

    【解决方案2】:

    type-def 也可以改进为使用重载:

      getReports(options?: ListingOptions & { only?: 'links' }): Listing<Submission | Comment>;
      getReports(options?: ListingOptions & { only: 'comments' }): Listing<Comment>;
    
    
    const reports = r.getReports(); // reports is Listing<Submission | Comment>
    
    const comments = r.getReports({ only: "comments" }); // comments is Listing<Comment>
    

    【讨论】:

      猜你喜欢
      • 2019-12-06
      • 2021-10-19
      • 1970-01-01
      • 2020-06-24
      • 2018-06-04
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多