typestar

validate-config.ts en TypeScript

Parsear entrada unknown a una config totalmente tipada o a una lista de problemas.

#!/usr/bin/env node
// Parsea y valida un objeto de config a una forma totalmente tipada.

interface Config {
  host: string;
  port: number;
  debug: boolean;
  tags: string[];
}

type Issue = { field: keyof Config; message: string };
type Parsed = { ok: true; config: Config } | { ok: false; issues: Issue[] };

function parseConfig(raw: Record<string, unknown>): Parsed {
  const issues: Issue[] = [];

  const host = typeof raw.host === "string" ? raw.host : "";
  if (!host) issues.push({ field: "host", message: "must be a string" });

  const port = typeof raw.port === "number" ? raw.port : NaN;
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    issues.push({ field: "port", message: "must be 1-65535" });
  }

  const debug = raw.debug === true;
  const tags = Array.isArray(raw.tags)
    ? raw.tags.filter((t): t is string => typeof t === "string")
    : [];

  if (issues.length > 0) return { ok: false, issues };
  return { ok: true, config: { host, port, debug, tags } };
}

const result = parseConfig({ host: "localhost", port: 8080, tags: ["dev"] });

if (result.ok) {
  console.log(`serving ${result.config.host}:${result.config.port}`);
  console.log(`tags: ${result.config.tags.join(", ") || "none"}`);
} else {
  for (const issue of result.issues) {
    console.error(`${issue.field}: ${issue.message}`);
  }
  process.exitCode = 1;
}

Cómo funciona

  1. Una unión discriminada Parsed reporta éxito o errores.
  2. Cada campo se chequea y recibe su valor por defecto individualmente.
  3. Un predicado de tipo filtra el arreglo de tags con seguridad.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
44
Caracteres a escribir
1314
Tokens
370
Ritmo de tres estrellas
105 tpm

Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 211 segundos.

Escribe este fragmento

Paso 1 de 1 en Bis; paso 23 de 23 en Tipos y anotaciones.

← Anterior