Home > Blockchain >  How to make an item in a fixed array of Promises optional using Typescript
How to make an item in a fixed array of Promises optional using Typescript

Time:10-23

I have something like this:

const promises:
            | [Promise<boolean>, Promise<boolean>]
            | [Promise<boolean>, Promise<boolean>, Promise<{ currency: string; price: number }>] = [
            User.is1337(user._id),
            PurchasedItemsModel.exists({
                type: 'course',
                userid: user._id,
                slug: courseSlug
            })
        ]

I want to type the promises variable properly.

Later down in the code I push to the promises array as follows:

promises.push(
                getSingleCoursePrice({
                    slug: courseSlug,
                    country,
                    percentOff: couponData?.percentOff || 0
                })
            )

and when I push like this, typescript gives me an error:

enter image description here

CodePudding user response:

Another workaround could be:

const promises: | [Promise<boolean>, Promise<boolean>, Promise<{ currency: string; price: number }> | undefined] = [
    User.is1337(user._id),
    PurchasedItemsModel.exists({
        type: 'course',
        userid: user._id,
        slug: courseSlug
    }),
    undefined // Will filter this out later
]

Now I can push whatever I want:

promises.push(Promise.resolve(true))
promises.push(Promise.resolve({ currency: '$', price: 1}))
promises.push(getSingleCoursePrice({
    slug: courseSlug,
    country,
    percentOff: couponData?.percentOff || 0
  })
)

Additional step that you will need to do at last:

promises.filter(o => o);

CodePudding user response:

I suppose you can use the following as a workaround:

    promises = [
        ...promises,
        getSingleCoursePrice({
            slug: courseSlug,
            country,
            percentOff: couponData?.percentOff || 0
        })
    ];

UPDATED:

TS Playground.

  • Related