← Fundamentals
Fundamentals

TypeScript catch, unknown, and thrown values

Identify what the kitchen threw, choose a notification policy, and observe a promised result at the right boundary.

Treat a caught value according to what the program can establish about it.

Outcome

Narrow an unknown catch value before reading it, give an Error subclass its own name, and keep a try open until the promise it guards has settled.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

unknown
A static type accepting any value. It can be passed, assigned and inspected with operations such as typeof; property access requires an appropriate narrowed or asserted view.
Narrowing
Control flow that gives a value a more specific checked type, using a condition such as typeof, instanceof or a discriminant test.
Error instance name
The name property read from an Error object. The default is inherited from Error.prototype, and the instance can supply an own value.
Rejected promise
A promise settled with a failure reason. Await observes that rejection as a throw; a promise rejection handler can process it too.

A caught value needs an observed shape

JavaScript can throw any value. Error is a useful convention for diagnostics, but a caller can also receive a string, object or another value. In the strict TypeScript workflow used here, an unannotated catch variable is unknown: the code must establish a suitable type before using type-specific properties.

Synchronous throws and promise rejections have different observation points. A promise represents an eventual result; code must observe its rejection through await or a rejection handler to decide how to report it. Follow both the value received and the operation that receives it.

01Anything can be thrown

Identify the value the kitchen threw

A noodle bar’s order screen asks the kitchen for each dish. The kitchen sometimes throws an Error, sometimes a plain string or an object, sometimes its own SoldOut class, and sometimes rejects a promise. The screen has to report every one of them sensibly without crashing.

The order screen receives failures from three kitchen calls. Each catch prints typeof and whether the value is an Error instance in this runtime. Predict the three classifications.

Each throw is caught by the same catch.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function describe(value: unknown): string {
  return `${typeof value} ${value instanceof Error}`;
}

const throws: (() => never)[] = [
  () => {
    throw "tea machine off";
  },
  () => {
    throw 42;
  },
  () => {
    throw new Error("soup has run out");
  }
];

for (const run of throws) {
  try {
    run();
  } catch (error) {
    console.log(describe(error));
  }
}
What are the three lines?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --strict --target ES2022 --module Node16 --moduleResolution Node16 --useDefineForClassFields true --outDir out main.ts && node out/main.js

Use a fresh directory for each supplied main.ts. Set the package.json type field to commonjs while preserving its other fields. The guarded command explicitly selects ES2022 and define-field semantics; run the emitted JavaScript only after the checker succeeds.

02Narrowing

Which view of a failure can the screen trust?

A string is thrown. The catch reads it once through as Error, and once through a reasonOf helper that narrows. Predict both lines.

reasonOf checks instanceof Error, then typeof "string", then falls back.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
function reasonOf(error: unknown): string {
  if (error instanceof Error) return error.message;
  if (typeof error === "string") return error;

  return "unknown failure";
}

try {
  throw "tea machine off";
} catch (error) {
  console.log(`as Error: ${(error as Error).message}`);
  console.log(`reasonOf: ${reasonOf(error)}`);
}
What does the first line print?

03Rejected promises

Observe the promised kitchen result

The screen requests ramen and receives a promise. Its consumer prints that the order was requested, then observes the promise inside try. Predict the consumer’s report.

cook returns a Promise<string>. main prints a request message before observing that result.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
async function cook(dish: string): Promise<string> {
  await Promise.resolve();
  throw new Error(`${dish} sold out`);
}

async function main() {
  const order = cook("ramen");
  console.log("order requested");

  try {
    await order;
    console.log("order ready");
  } catch (error) {
    const reason = error instanceof Error ? error.message : "unrecognized failure";
    console.log(`kitchen refused: ${reason}`);
  }
}

void main();
Which lines does the consumer print?

04Repair the order screen

A reason for anything, a named failure, a caught rejection

The order screen needs three repairs. First show safe failure notifications while keeping cancellation quiet. Then identify the SoldOut instance correctly. Finally keep rejected orders within the placeOrder boundary.

The lab file contains its imports, the reader, the supplied kitchen and a complete main.

Repair the order screen

Narrowing an unknown value, a subclass’s name, then a rejection the try must await.

  1. easy · F-UNKNOWN-V4-1 Show a safe failure notification
  2. medium · F-UNKNOWN-V4-2 Name the sold-out failure
  3. hard · F-UNKNOWN-V4-3 Catch the rejected order
In the frontend Passing a handler versus calling it Optional

A parent can pass a caught value to a read-only status label. The component checks the value before choosing an Error label or a typeof category.

FailureKind.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Props = { failure: unknown };

export function FailureKind({ failure }: Props) {
  const kind = failure instanceof Error ? "Error object" : typeof failure;
  return <span>{kind}</span>;
}

The prop remains unknown at the component boundary. The expression classifies it against the current realm’s Error constructor; null is an object category, not an Error instance. The component renders a string category rather than the unknown value.

Sources: React: passing props to a component,Svelte: derived state.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.