将具有两种类型的TypeScript数组过滤为仅一种类型

时间:2018-04-20 13:50:32

标签: typescript

我尝试使用snoowrap Reddit API wrapper从subreddit获取报告的Comment对象列表。 getReports方法返回类型为Submission | Comment的数组,但您可以将参数传递给它,以便仅返回返回数据中的注释。

然而它仍然作为一个包含两种类型的数组返回,所以我想使用一个过滤器来保留那些是Comment类型的过滤器。这只会修改项目,并且不会将数组的类型更改为仅注释。

这是我尝试的内容:

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对象。

有什么建议吗?感谢。

2 个答案:

答案 0 :(得分:1)

如果您已经知道只有评论,则可以将其转换为您想要的类型。

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

答案 1 :(得分:0)

同样可以改进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>