Dev Helpers
← Back

Return a typed result from a caught rejection

Return a typed result from a caught rejection using TypeScript.

Open this example in the interactive library

Source code

const load = async (id: number): Promise<{ id: number; ready: boolean }> => ({
  id,
  ready: true,
});
console.log(
  await (async (): Promise<{ ok: false; reason: string }> => {
    try {
      await Promise.reject(new Error("late"));
    } catch (e) {
      return { ok: false, reason: e instanceof Error ? e.message : "unknown" };
    }
    return { ok: false, reason: "empty" };
  })(),
);

Sample output

{ ok: false, reason: 'late' }