Back to code TypeScript

Errores sin excepciones: el tipo Result

Un tipo de dos variantes que obliga al compilador a recordarte que la operación puede fallar.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

Una función que lanza excepciones no lo dice en su firma: quien la llama se entera en producción. Con un Result, olvidarse de manejar el error no compila.

TypeScript
type Result<T, E = string> = { ok: true; valor: T } | { ok: false; error: E };

function parsearMonto(texto: string): Result<number> {
  const n = Number(texto.replace(",", "."));
  if (Number.isNaN(n)) return { ok: false, error: `"${texto}" no es un número` };
  if (n < 0) return { ok: false, error: "el monto no puede ser negativo" };
  return { ok: true, valor: Math.round(n * 100) / 100 };
}

const r = parsearMonto("149,90");
if (r.ok) {
  console.log("Cobrar", r.valor.toFixed(2));
} else {
  console.error("Rechazado:", r.error);
}

Why it is written this way

  1. Result es una unión discriminada: el campo ok le dice a TypeScript cuál de las dos formas tiene delante.
  2. Dentro del if (r.ok) el compilador sabe que existe r.valor; en el else, que existe r.error. Usar el campo equivocado no compila.
  3. La función nunca lanza: todo lo que puede salir mal está en el tipo de retorno.
  4. El redondeo a dos decimales evita arrastrar 149.89999 a una factura.
How to try it

Guardalo como monto.ts y corré: npx tsx monto.ts. Probá cambiar la entrada por "abc" o "-5".

Watch out

Result no reemplaza a las excepciones para lo inesperado (disco lleno, bug). Sirve para los fallos que son parte normal del negocio: un dato mal escrito, un saldo insuficiente.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Uso este tipo Result en TypeScript. Escribime las funciones auxiliares map, andThen y unwrapOr para encadenar operaciones sin anidar if, y mostrame cómo quedaría validar este formulario con ellas: [CAMPOS Y REGLAS]. Mantené el tipado estricto, sin any, y sin librerías.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.