Home > Blockchain >  How to check actual type of a union type in Typescript?
How to check actual type of a union type in Typescript?

Time:07-04

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?

CodePudding user response:

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

  • Related