typescript-best-practices
0xbigboss/claude-code
Enforce type safety and prevent invalid states in TypeScript and JavaScript code.
What is typescript-best-practices?
This skill applies type-first and functional patterns to TypeScript/JavaScript files (.ts, .tsx, .js, tsconfig.json). Use it when reading or writing TypeScript code to leverage the type system for compile-time correctness and runtime validation.
- Make illegal states unrepresentable using discriminated unions and branded types
- Validate runtime data with Zod schemas as single source of truth
- Use exhaustive switch checks with never types to catch missing cases
- Compose and transform schemas to keep types and validation in sync
- Leverage type-fest utilities for advanced type operations
How to install typescript-best-practices
npx skills add https://github.com/0xbigboss/claude-code --skill typescript-best-practices- TypeScript or JavaScript project
- Zod library (optional but recommended for runtime validation)
- type-fest library (optional for advanced type utilities)
How to use typescript-best-practices
- 1.Define discriminated unions or branded types for domain concepts to prevent invalid states
- 2.Use Zod schemas as single source of truth for data structures, inferring TypeScript types with z.infer<>
- 3.Apply safeParse for user input validation and parse at trust boundaries
- 4.Add exhaustive switch checks with never types to catch unhandled cases
- 5.Compose schemas with extend(), pick(), omit(), merge() and transform() for normalization
Use cases
- Preventing invalid state combinations in request handlers or UI state machines
- Validating API responses and form inputs with Zod at trust boundaries
- Ensuring all union type cases are handled in switch statements
- Creating domain-specific branded types to prevent mixing incompatible IDs
- Building reusable schema compositions for DRY validation logic
- TypeScript developers
- Backend API developers
- Frontend engineers building type-safe applications
- Teams using Zod for runtime validation
typescript-best-practices FAQ
Use discriminated unions when states are mutually exclusive (e.g., loading, success, error). They prevent invalid combinations at compile time. Optional fields allow any combination, which is error-prone.
Use parse at trust boundaries (API responses, database reads) where invalid data is a bug. Use safeParse for user input where failure is expected and should be handled gracefully.
Define the Zod schema first, then infer the TypeScript type with z.infer<typeof Schema>. This single source of truth prevents duplication and drift.
A branded type uses TypeScript's type system to distinguish semantically different strings or numbers (e.g., UserId vs. OrderId). Use it to prevent accidentally passing the wrong ID to a function.
TypeScript builtins (Partial, Pick, Omit, etc.) cover most cases. type-fest adds utilities like Opaque for cleaner branded types and PartialDeep for recursive partials on nested objects.
Full instructions (SKILL.md)
Source of truth, from 0xbigboss/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
safeParsefor user input where failure is expected; useparseat 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 }patternPartialDeep<T>- recursive partial for nested objectsReadonlyDeep<T>- recursive readonly for immutable dataSetRequired<T, K>/SetOptional<T, K>- targeted field modificationsSimplify<T>- flatten complex intersection types in IDE tooltips
import type { Opaque, PartialDeep } from 'type-fest';
type UserId = Opaque<string, 'UserId'>;
type UserPatch = PartialDeep<User>;
Related skills
More from 0xbigboss/claude-code and the wider catalog.

web-fetch
Fetches web content as clean markdown by preferring markdown-native responses and falling back to selector-based HTML extraction. Use for documentation, articles, and reference pages at http/https URLs.

python-best-practices
Type-first Python patterns: immutable models, discriminated unions, and structured error handling.

react-best-practices
Use Effects as escape hatches, prefer event handlers and render-time calculations for React component logic.

design-lab
Conduct design interviews, generate five distinct UI variations in a temporary design lab, collect feedback, and produce implementation plans. Use when the user wants to explore UI design options, redesign existing components, or create new UI with multiple approaches to compare.

risk-management
Data-driven risk rules from 8500 trading samples to optimize position sizing and trade frequency.

trading-wisdom
Core trading insights learned from Agent Arena competition. Use when making any trading decision to apply institutional knowledge.