Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuro

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
012345678901234567890123456789012345678901234567890123456789
Ieri
012345678901234567890123456789012345678901234567890123456789
Visualizzazioni totali
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di TypeScript
TypeScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: The Type System
Discussioni

Guida a TypeScript · 5/6

Errors and Testing

Per ora questo capitolo è disponibile solo in inglese.

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.

Domande su questo capitolo?
Capitolo precedenteModules and PackagesCapitolo successivoKey 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 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.