Saltar al contenido
AKOS
Todos los packs
StableFrontendtypescript

TypeScript — Type Safety Practice

Operationalizes TypeScript as a correctness tool: strict mode, narrow types over any, discriminated unions for state, and schema validation at boundaries.

typescripttype-safetystrict-modediscriminated-unionsschema-validation

Principios

  • · TS1 — strict: true in tsconfig from project start; retrofitted incrementally if inherited loose.
  • · TS2 — any is never used without an explicit, reviewed justification comment; prefer unknown + narrowing.
  • · TS3 — State with mutually exclusive variants is modeled as a discriminated union, not multiple optional fields.
  • · TS4 — External data (API responses, form input, env vars) is validated against a schema at the boundary (Zod/io-ts/similar), not cast.
  • · TS5 — Function signatures express real constraints (non-empty arrays, branded IDs) rather than the loosest type that compiles.

Patrones

  • · Grep for any and as — each is a candidate for narrowing to a real type.
  • · Multiple optional booleans on one type (isLoading?, isError?, data?) → likely should be a discriminated union ({status:'loading'} | {status:'error',error} | {status:'success',data}).
  • · Data crossing a network/file/env boundary without a schema validator → add one; don't trust JSON.parse(...) as MyType.
  • · A function accepting string when it really means "a UUID" or "an email" → consider a branded type if misuse is a real risk.

Riesgos

  • · as MyType casting API responses — no runtime validation, type is a lie at the boundary.
  • · any escape hatches accumulating — each one disables checking for everything downstream.
  • · Boolean flag soup for state — {isLoading, isError, hasData} allowing impossible combinations (isLoading && isError).
  • · // @ts-ignore instead of fixing the type — silences the error without addressing the underlying issue.
  • · Non-null assertion (!) as a habit — bypassing null checks the type system correctly flagged.

Checklist

  • [ ] strict mode enabled. (TE1)
  • [ ] No unjustified any. (TE2)
  • [ ] External data schema-validated at the boundary. (TE3)
  • [ ] Mutually exclusive state modeled as discriminated unions. (TE4)
  • [ ] Type assertions rare and justified. (TE5)
  • [ ] No any/unknown leaking into public API surfaces. (TE6)

Fuentes

En la bibliografía AKOS

Este pack cita las siguientes fuentes registradas en el índice bibliográfico:

Explorar todas las fuentes →