Tom Finet
Tom Finet

Reputation: 485

How to check actual type of a union type in Typescript?

I am making the following function call:

const page : (Nft | null)[] = await metaplex.nfts().findAllByMintList(mintAddressPage);

Which returns a type of (Nft | null)[]. I want to be able to check that page is in fact of type Nft[] before further operations are performed on it. How can I make it so that page has type Nft[] only after the check passes successfully?

Upvotes: 1

Views: 1247

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 55072

You might want to use predicates to filter your array :

const maybePages: (Nft | null)[] = await metaplex.nfts().findAllByMintList(mintAddressPage);

const pages = maybePages.filter((page: Nft | null): page is Nft => page !== null)

Playground

Upvotes: 1

Related Questions