Estrechamiento en TypeScript
El compilador sigue tus chequeos: typeof, in, instanceof y valores truthy.
type Success = { ok: true; value: string };
type Failure = { ok: false; error: Error };
type Outcome = Success | Failure;
function describe(outcome: Outcome): string {
if (outcome.ok) return outcome.value.toUpperCase();
return outcome.error.message;
}
function describeUnion(input: string | number | Date | null): string {
if (input === null) return "nothing";
if (typeof input === "string") return input.trim();
if (typeof input === "number") return input.toFixed(1);
return input.toISOString();
}
function hasSteps(value: { steps?: number[] } | { slug: string }): boolean {
return "steps" in value && (value.steps?.length ?? 0) > 0;
}
console.log(describe({ ok: true, value: "done" }));
console.log(describeUnion(new Date(0)), hasSteps({ steps: [1] }));
Cómo funciona
inestrecha una unión por la presencia de una propiedad.instanceofestrecha clases;typeofestrecha primitivos.- Una propiedad discriminante es el estrechamiento más legible de todos.
Palabras clave y builtins usados aquí
DateErrorOutcomebooleanfalsefunctionifnumberreturnstringtruetype
El intento, en números
- Líneas
- 22
- Caracteres a escribir
- 759
- Tokens
- 212
- Ritmo de tres estrellas
- 95 tpm
Al ritmo de tres estrellas de 95 tokens por minuto, este intento toma unos 134 segundos.
Paso 2 de 4 en Estrechamiento; paso 8 de 23 en Tipos y anotaciones.