将两种类型的TypeScript数组筛选为一种类型

将两种类型的TypeScript数组筛选为一种类型,typescript,Typescript,我正在尝试使用从子Reddit获取报告的注释对象列表。getReports方法返回一个类型为Submission | Comment的数组,但您可以向其中传递一个参数,以仅获取返回数据中的注释 但是,它仍然返回为两种类型的数组,因此我想使用一个过滤器来只保留注释类型的数组。这只会修改项目,不会将数组的类型更改为注释 以下是我正在尝试的: getReportedComments(): Comment[] { return this.r .getSubreddit("subr

我正在尝试使用从子Reddit获取报告的注释对象列表。
getReports
方法返回一个类型为
Submission | 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)
}
getReportedComments():Comment[]{
把这个还给我
.getSubreddit(“subreddit”)
.getReports({only:“comments”})//返回一个列表,它只是数组的一个子类
.filter(comment=>comment instanceof comment)
}
r
是Snoowrap对象


有什么建议吗?谢谢。

如果您已经知道只有注释,您可以将其转换为您想要的类型

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

此外,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>
getReports(选项?:列表选项&{only?:'links}):列表;
getReports(选项?:ListingOptions&{only:'comments'}):列表;
const reports=r.getReports();//报告正在列表中
const comments=r.getReports({only:“comments”});//评论正在列表中
当您说它“仍然作为两种类型的数组返回”时,您的意思是返回类型仍然包括这两种类型,还是在运行时请求实际上返回时填充了这两种类型?