cogm
cogm

Reputation: 285

Filtering TypeScript array with two types to just one type

I'm trying to use the snoowrap Reddit API wrapper to get a list of reported Comment objects from a subreddit. The getReports method returns an array of type Submission | Comment, but you can pass a parameter in to it to get only Comments in the returned data.

However it still comes back as an array with both types, so I wanted to use a filter to only keep the ones that are Comment type. This only modifies the items, and doesn't change the type of the array to just Comments.

Here's what I'm trying:

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 is a Snoowrap object.

Any advice? Thanks.

Upvotes: 0

Views: 2097

Answers (2)

Aaron Beall
Aaron Beall

Reputation: 52143

Also the type-def could probably be improved to use an overload:

  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>

Upvotes: 0

rm4
rm4

Reputation: 721

If you already know that there is only comments, you can cast it to the type you want.

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

Upvotes: 1

Related Questions