Skip to content

Typed Promises

The Course
•
25 min study

Before today, revisit JavaScript intermediate's promises and async/await. A Promise<T> describes a future fulfillment value T. An async function returning a number produces Promise<number>, not number immediately.

Await gives you the fulfilled value or throws a rejection. TypeScript describes the fulfillment type; it does not restrict a promise to rejecting with one declared error type. Catch values therefore remain unknown under strict checking. A Result<T> can make expected failure part of the fulfilled value when that is the contract you choose.

These TypeScript editors run isolated ES modules. They support top-level await, so the example explicitly awaits completion before the runner ends. This differs from the older JavaScript editor's main() entry convention. For an async helper, end a program with await main() if it must finish before output is collected. Unawaited background work is not kept alive by the runner.

A type annotation does not initiate network I/O or make a synchronous computation concurrent. Our examples use deterministic local promises, and normal completion must fit the playground's three-second execution limit.

Recall the JavaScript behavior first

Before adding promise types, explain what happens when an async function returns, throws, and awaits a rejected promise. If you cannot predict those three outcomes yet, revisit the linked JavaScript lessons above. Today's types describe those existing behaviors rather than replacing them. Before the next two lessons, also refresh injected dependencies and AbortSignal cancellation. JavaScript advanced is optional for this course.

Predict, run, and explain

Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.

Predict, then runTypeScript
async function countBooks(): Promise<number> {
  return 2;
}

const pending = countBooks();
const count = await pending;

console.log(count + 1);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
3

Read the compiler error

An async return is a promise; the fulfillment value is not available yet.

Find and fix the type errorTypeScript
async function count(): Promise<number> {
  return 2;
}

const total: number = count();

console.log(total);

Enable JavaScript to edit and type-check this example.

Check your diagnosis

Await count() before assigning it to a number. This editor is an ES module, so top-level await is supported.

Type the future value and await its availability

Promise<T> describes fulfillment data, not an immediately available T. Calling an async function begins executing its body and returns a promise; await obtains its value or throws its rejection. The type annotation does not initiate a network request or make CPU work parallel.

A fulfillment type also does not restrict rejection reasons. Use a Result when expected failure should be part of fulfilled data, while still recognizing that programming errors can reject the function. Keep those two failure policies distinct.

A promise before and after awaitTypeScript
async function load(): Promise<number> {
  return 0;
}

const pending = load();

console.log(typeof pending.then);

const value = await pending;

console.log(value + 1);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
function
1

The promise offers coordination methods; the awaited number offers arithmetic. Assigning pending directly to a number would lose the availability distinction and must fail checking.

An awaited Result still needs narrowingTypeScript
type Result<T> =
  | {
      ok: true;

      value: T;
    }
  | {
      ok: false;

      message: string;
    };

async function load(): Promise<Result<number>> {
  return { ok: false, message: "Expected failure" };
}

const result = await load();

console.log(result.ok ? result.value : result.message);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Expected failure

This call fulfills with a failure variant rather than rejecting. A caller handles it by narrowing the result; a catch alone would not observe this expected failure.

Try the rule on new inputs

Compare a thrown Error with a fulfilled error variant. State what await does for each. Explicitly await the intended work in this module editor so its output is collected before the run ends.

Debug a plausible mistake

Exercise

Repair a rejection assumption

Print the rejection reason offline. Keep catch values unknown and support both Error objects and other thrown values; do not assert every rejection is Error.

Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.

Find and fix the type errorTypeScript
async function load(): Promise<number> {
  throw "offline";
}

try {
  await load();
} catch (error) {
  console.log(error.message);
}

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

Promise<number> describes fulfillment, not the set of possible rejection reasons.

Hint 2: a first step

Narrow with instanceof Error before reading message; otherwise format the actual value.

Show one solution
TypeScript
async function load(): Promise<number> {
  throw "offline";
}

try {
  await load();
} catch (error) {
  if (error instanceof Error) {
    console.log(error.message);
  } else {
    console.log(String(error));
  }
}
Text
offline

Under strict checking a catch variable is unknown, so reading error.message directly was a compile error (TS18046). That is not pedantry: this load throws a plain string, which has no message property, so the original would have printed undefined. instanceof Error narrows the first branch; String(error) handles everything else, which is why "offline" prints.

Your turn

Exercise

Typed Promises: practice

Write an async label function accepting a title:string and returning Promise<string>. Await it for Types and print Book: Types. Do not cast the promise to a string.

Your workspaceTypeScript
// Use top-level await in this TypeScript module editor.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The async function returns a promise even when its body returns text directly.

Hint 2: a first step

Declare Promise<string> as the return and await the call before logging.

Show one solution
One possible solutionTypeScript
async function label(title: string): Promise<string> {
  return `Book: ${title}`;
}

console.log(await label("Types"));

Enable JavaScript to edit and type-check this example.

Text
Book: Types

An async function always returns a promise, so the annotation is Promise<string> even though the body returns a plain string; const text: string = label("Types") would be rejected with TS2322. await unwraps the promise to the string that the template literal needs. The checker confirms the types line up; only running it shows the "Book: " prefix is right.

Change it and test it

Try calling toUpperCase on the unawaited promise and read the compiler error. Then await it and call the method on the string. Explain why Promise<string> tells you nothing about the exact rejection value.

Was this article helpful?

Your response is saved on this device.