本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペースはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらく

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシープライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
012345678901234567890123456789012345678901234567890123456789
昨日
012345678901234567890123456789012345678901234567890123456789
累計閲覧
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

TypeScript ドキュメント
TypeScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: The Type System
ディスカッション

TypeScript ガイド · 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.

この章について質問がありますか?
前の章Modules and Packages次の章Key Concepts: The Type System
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.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。