PluginBench
Skill
Pass
Audit score 90

typescript-best-practices

alleneubank/claude-code

TypeScript patterns for type-safe, error-resistant code using discriminated unions, branded types, and runtime validation.

What is typescript-best-practices?

Guidance on TypeScript idioms for making invalid states unrepresentable at compile time and validating runtime data safely. Use when reading or writing TypeScript, JavaScript, or configuration files. Pairs with react-best-practices for React component work.

  • Prevent invalid state combinations using discriminated unions and branded types
  • Enforce exhaustive pattern matching with never-type checks
  • Validate external data with Zod schemas as single source of truth
  • Infer TypeScript types from Zod schemas to keep types and validation in sync
  • Normalize and transform data at parse time using Zod transforms
  • Leverage type-fest utilities for advanced type operations

How to install typescript-best-practices

npx skills add https://github.com/alleneubank/claude-code --skill typescript-best-practices
Prerequisites
  • TypeScript 4.4+ (for const assertions and other modern features)
  • Zod library (optional but recommended for runtime validation)
  • type-fest library (optional, for advanced type utilities)
Claude Code
Cursor
Windsurf
Cline

How to use typescript-best-practices

  1. 1.Load this skill when working on .ts, .tsx, .js, or tsconfig.json files
  2. 2.For React components, also load react-best-practices alongside this skill
  3. 3.Use discriminated unions instead of optional boolean flags for mutually exclusive states
  4. 4.Define Zod schemas as source of truth and infer types with z.infer<>
  5. 5.Use safeParse for untrusted input and parse at trust boundaries
  6. 6.Apply const assertions to literal arrays and use exhaustive switch checks

Use cases

Good for
  • Designing request/response state machines that prevent loading+error simultaneously
  • Validating API responses at trust boundaries to catch contract violations early
  • Building form handlers that safely parse user input and report field-level errors
  • Creating domain types (UserId, OrderId) that prevent accidental type mismatches at compile time
  • Refactoring boolean flag combinations into discriminated unions for clarity
Who it's for
  • TypeScript developers writing type-safe applications
  • Backend engineers validating API contracts
  • Frontend developers building forms and state management
  • Teams using Zod for runtime schema validation

typescript-best-practices FAQ

When should I use safeParse vs parse with Zod?

Use safeParse when parsing user input where failure is expected (forms, API calls); it returns a result object. Use parse at trust boundaries (internal APIs, database reads) where invalid data indicates a bug; it throws on failure.

How do I keep types and Zod schemas in sync?

Define the Zod schema first, then infer the TypeScript type with z.infer<typeof MySchema>. This single source of truth prevents duplication and drift.

What's the advantage of branded types over enums?

Branded types (UserId, OrderId) are nominal types that prevent accidental mixing at compile time while remaining strings at runtime. Enums create actual objects and can cause issues with tree-shaking and module boundaries.

How do I handle nested optional fields with Zod?

Use z.object().optional() for optional objects, z.array().optional() for optional arrays, or compose with .extend() and .pick()/.omit() for partial updates.

Should I use type-fest for all advanced types?

type-fest is optional. Use it when TypeScript builtins (Partial, Readonly, Pick, Omit) don't cover your need, such as recursive partial types or opaque branded types.

Full instructions (SKILL.md)

Source of truth, from alleneubank/claude-code.


name: typescript-best-practices description: Use when reading or writing TypeScript or JavaScript files (.ts, .tsx, .js, tsconfig.json).

TypeScript Best Practices

Follows type-first, functional, and error handling patterns from CLAUDE.md. This skill covers language-specific idioms only.

Pair with React Best Practices

When working with React components (.tsx, .jsx files or @react imports), always load react-best-practices alongside this skill. This skill covers TypeScript fundamentals; React-specific patterns (effects, hooks, refs, component design) are in the dedicated React skill.

Make Illegal States Unrepresentable

Use the type system to prevent invalid states at compile time.

Discriminated unions for mutually exclusive states:

// Good: only valid combinations possible
type RequestState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: Error };

// Bad: allows invalid combinations like { loading: true, error: Error }
type RequestState<T> = {
  loading: boolean;
  data?: T;
  error?: Error;
};

Branded types for domain primitives:

type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };

// Compiler prevents passing OrderId where UserId expected
function getUser(id: UserId): Promise<User> { /* ... */ }

Const assertions for literal unions:

const ROLES = ['admin', 'user', 'guest'] as const;
type Role = typeof ROLES[number]; // 'admin' | 'user' | 'guest'

// Array and type stay in sync automatically
function isValidRole(role: string): role is Role {
  return ROLES.includes(role as Role);
}

Exhaustive switch with never check:

type Status = "active" | "inactive";

function processStatus(status: Status): string {
  switch (status) {
    case "active":
      return "processing";
    case "inactive":
      return "skipped";
    default: {
      const _exhaustive: never = status;
      throw new Error(`unhandled status: ${_exhaustive}`);
    }
  }
}

Runtime Validation with Zod

  • Define schemas as single source of truth; infer TypeScript types with z.infer<>. Avoid duplicating types and schemas.
  • Use safeParse for user input where failure is expected; use parse at trust boundaries where invalid data is a bug.
  • Compose schemas with .extend(), .pick(), .omit(), .merge() for DRY definitions.
  • Add .transform() for data normalization at parse time (trim strings, parse dates).
import { z } from "zod";

const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  name: z.string().min(1),
  createdAt: z.string().transform((s) => new Date(s)),
});

type User = z.infer<typeof UserSchema>;

// Strict parsing at trust boundaries — throws if API contract violated
export async function fetchUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) {
    throw new Error(`fetch user ${id} failed: ${response.status}`);
  }
  return UserSchema.parse(await response.json());
}

// Caller handles both success and error from user input
const result = UserSchema.safeParse(formData);
if (!result.success) {
  setErrors(result.error.flatten().fieldErrors);
  return;
}

Optional: type-fest

For advanced type utilities beyond TypeScript builtins, consider type-fest:

  • Opaque<T, Token> - cleaner branded types than manual & { __brand } pattern
  • PartialDeep<T> - recursive partial for nested objects
  • ReadonlyDeep<T> - recursive readonly for immutable data
  • SetRequired<T, K> / SetOptional<T, K> - targeted field modifications
  • Simplify<T> - flatten complex intersection types in IDE tooltips
import type { Opaque, PartialDeep } from 'type-fest';

type UserId = Opaque<string, 'UserId'>;
type UserPatch = PartialDeep<User>;