Typescript Best Practices

alleneubank/claude-code/.claude/skills/typescript-best-practices

作者 alleneubank2921eb8a685a無授權條款52 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫3 個月前更新

Use when reading or writing TypeScript or JavaScript files (.ts, .tsx, .js, tsconfig.json).

已封存僅含說明Software Development
AI 產生的概覽

以型別優先、函式式與錯誤處理模式指導 TypeScript 與 JavaScript 編碼。

功能
此技能提供 TypeScript 與 JavaScript 的語言層級慣用法,包括可辨識聯合、品牌型別、const 斷言、窮盡 switch 檢查以及 Zod 執行期驗證。它建議在處理 React 元件時搭配另一個 React 技能使用,並提到選用的 type-fest 工具型別。它產出的是指引與程式碼模式,而非檔案或指令碼。
適用情境
在閱讀或撰寫 TypeScript、JavaScript 檔案(例如 .ts、.tsx、.js 或 tsconfig.json)時使用。它著重語言層面的模式,不涉及 React 元件設計,後者交由另一個技能處理。
執行需求
除代理本身外無需指令碼或工具。指引中提及 Zod 函式庫以及選用的 type-fest,並假定專案使用 TypeScript 或 JavaScript。

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:

ts
// Good: only valid combinations possibletype 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:

ts
type UserId = string & { readonly __brand: 'UserId' };type OrderId = string & { readonly __brand: 'OrderId' };
// Compiler prevents passing OrderId where UserId expectedfunction getUser(id: UserId): Promise<User> { /* ... */ }

Const assertions for literal unions:

ts
const ROLES = ['admin', 'user', 'guest'] as const;type Role = typeof ROLES[number]; // 'admin' | 'user' | 'guest'
// Array and type stay in sync automaticallyfunction isValidRole(role: string): role is Role {  return ROLES.includes(role as Role);}

Exhaustive switch with never check:

ts
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).
ts
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 violatedexport 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 inputconst 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
ts
import type { Opaque, PartialDeep } from 'type-fest';
type UserId = Opaque<string, 'UserId'>;type UserPatch = PartialDeep<User>;

來源與署名

來源:alleneubank/claude-code位於.claude/skills/typescript-best-practices提交2921eb8

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架