typestar

Uniones discriminadas en TypeScript

Un campo literal compartido que vuelve exhaustiva una unión.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number }
  | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "rect":
      return shape.width * shape.height;
    case "square":
      return shape.side ** 2;
  }
}

Cómo funciona

  1. Cada miembro lleva un kind distinto.
  2. Un switch sobre kind estrecha a ese miembro.
  3. Cubrir todos los casos satisface el tipo de retorno.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
15
Caracteres a escribir
338
Tokens
93
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 51 segundos.

Escribe este fragmento

Paso 1 de 3 en Exhaustividad y pruebas; paso 9 de 12 en Programación a nivel de tipos.

← Anterior Siguiente →