How to use promise.allSettled with typescript?

Like bela53 stated, use type guards. A more elegant solution than to inline the type guards is to define them as separate functions, and with generics binding you’d get the correct value too for the fulfilled promises, and can reuse for any allSettled filtering needs.

Casting is not needed (and generally should be avoided).

const isRejected = (input: PromiseSettledResult<unknown>): input is PromiseRejectedResult => 
  input.status === 'rejected'

const isFulfilled = <T>(input: PromiseSettledResult<T>): input is PromiseFulfilledResult<T> => 
  input.status === 'fulfilled'

const myPromise = async () => Promise.resolve("hello world");

const data = await Promise.allSettled([myPromise()]);

const response = data.find(isFulfilled)?.value
const error = data.find(isRejected)?.reason

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)