Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack safer

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
012345678901234567890123456789012345678901234567890123456789
Yesterday
012345678901234567890123456789012345678901234567890123456789
Total views
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

TypeScript docs
TypeScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: The Type System
Discussions

TypeScript guide · 5/6

Errors and Testing

Error handling in TypeScript uses the same throw and try...catch you know from JavaScript. The type system makes it safer, though, and it opens up an alternative: describing failure in the return type itself. This chapter covers unknown catch variables, custom error classes, and the result pattern, and then shows how to write tests with Vitest and with the test runner built into Node.js.

try...catch and unknown

JavaScript lets you throw anything, not just Error objects; throw "oops" is perfectly legal. To reflect that, strict mode types the catch variable as unknown (via the useUnknownInCatchVariables option). You have to establish what it is before touching its properties.

function parseConfig(text: string): Record<string, unknown> {
  try {
    return JSON.parse(text);
  } catch (err) {
    // err: unknown
    if (err instanceof SyntaxError) {
      console.error("Malformed JSON:", err.message);
    } else {
      console.error("Unexpected failure:", err);
    }
    return {};
  } finally {
    console.log("Finished reading config");
  }
}

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : String(err);
}

A tiny helper like errorMessage saves you from repeating the same check in every log statement. In async functions, placing the await inside the try block catches rejected promises the same way.

Custom error classes

Subclassing Error lets you tell failures apart by class and attach extra data as properties. Setting name makes the error type stand out in logs, and the cause option links a new error to the one that triggered it.

class NotFoundError extends Error {
  constructor(
    public readonly resource: string,
    options?: ErrorOptions,
  ) {
    super(`Not found: ${resource}`, options);
    this.name = "NotFoundError";
  }
}

async function loadUser(id: string): Promise<{ id: string; name: string }> {
  try {
    const res = await fetch(`https://api.example.com/users/${id}`);
    if (res.status === 404) throw new NotFoundError(`user ${id}`);
    return await res.json();
  } catch (err) {
    if (err instanceof NotFoundError) throw err;
    throw new Error("Could not load user", { cause: err });
  }
}

For instanceof to recognize subclasses reliably, compile with a target of ES2015 or later. ErrorOptions and cause come from the ES2022 library typings, so set target or lib accordingly.

The result pattern

Exceptions are invisible in a function's signature: nothing in the types tells a caller what might be thrown. For failures that are an expected part of normal operation, such as validating user input, you can return a value that represents either success or failure.

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

function parseAge(input: string): Result<number, string> {
  const age = Number(input);
  if (!Number.isInteger(age) || age < 0) {
    return { ok: false, error: `Not a valid age: ${input}` };
  }
  return { ok: true, value: age };
}

const result = parseAge("42");
if (result.ok) {
  console.log(result.value + 1);  // value is available here
} else {
  console.error(result.error);    // and error is available here
}

Because the ok flag separates the two cases, the compiler refuses any attempt to read value before checking for failure. A sensible split is to throw for genuine bugs and unexpected conditions, and to return results for failures the caller is expected to handle.

Testing with Vitest

Vitest runs TypeScript test files with zero configuration. Start with something to test:

// src/math.ts
export function divide(a: number, b: number): number {
  if (b === 0) throw new RangeError("Cannot divide by zero");
  return a / b;
}
// src/math.test.ts
import { describe, it, expect } from "vitest";
import { divide } from "./math.js";

describe("divide", () => {
  it("returns the quotient", () => {
    expect(divide(10, 4)).toBe(2.5);
  });

  it("throws a RangeError on division by zero", () => {
    expect(() => divide(1, 0)).toThrow(RangeError);
  });

  it("works with async assertions too", async () => {
    await expect(Promise.resolve(divide(9, 3))).resolves.toBe(3);
  });
});
npm install --save-dev vitest
npx vitest          # watch mode, reruns on change
npx vitest run      # single run, for CI

Like most fast tooling, Vitest strips types without checking them. Run tsc --noEmit as a separate step.

The built-in Node.js test runner

If you would rather avoid another dependency, Node.js ships node:test and node:assert. Load tsx as a module hook so Node can execute the .ts files.

// src/math.node.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { divide } from "./math.js";

test("divide computes the quotient", () => {
  assert.equal(divide(10, 4), 2.5);
});

test("divide rejects a zero divisor", () => {
  assert.throws(() => divide(1, 0), RangeError);
});
node --import tsx --test src/math.node.test.ts

Summary

  • Catch variables are unknown; narrow them with checks such as instanceof Error first.
  • Subclass Error to distinguish failure kinds, and record context with name and cause.
  • Model expected failures with a result type built from { ok: true } and { ok: false } variants.
  • Vitest runs .ts tests without setup; node:test needs no extra dependency at all.
  • Test runners skip type checking, so keep tsc --noEmit in the pipeline.
Questions about this chapter?
Previous chapterModules and PackagesNext chapterKey Concepts: The Type System

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.