Type Patterns
Overview
Patterns for defining and using TypeScript types effectively. Prefer discriminated unions for variant modeling, branded types for domain safety, and utility types to avoid repetition. These rules apply to all type definitions in the monorepo.
Rules
Use Discriminated Unions for Variants
Define a common discriminator field (usually type, kind, or strategy) that TypeScript uses to narrow the type. Combine with match from massaman/match for exhaustive matching.
Correct
Use type-fest for Common Utilities
type-fest provides type utilities not included in TypeScript's standard library. It is installed under @ciderpress/config and @ciderpress/theme — prefer LiteralUnion, Simplify, SetRequired, PartialDeep, etc. over hand-rolled equivalents.
Correct
Write Type Guards for Runtime Checks
Create custom type guard functions that return value is T for runtime type narrowing.
Correct
Incorrect
Use Built-in Utility Types
TypeScript ships utility types for common transformations. Use them instead of hand-rolling equivalents.
Correct
Use Branded Types for Domain Safety
Use branded types to prevent mixing up structurally identical primitives.
Correct
Incorrect
Use Const Assertions for Literal Types
Use as const for literal types, readonly arrays, and deriving union types from values.
Correct
Incorrect
Resources
References
- Conditionals -- Using discriminated unions with
massaman/match