Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguro

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
012345678901234567890123456789012345678901234567890123456789
Ayer
012345678901234567890123456789012345678901234567890123456789
Vistas totales
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de TypeScript
TypeScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: The Type System
Debates

Guía de TypeScript · 5/6

Errors and Testing

Por ahora, este capítulo solo está disponible en inglés.

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.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorModules and PackagesCapítulo siguienteKey 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 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.