← 返回列表
全部 Skill›工具 Tools›typescript-patterns

typescript-patterns

作者 @affaan-m · 语言 en
TypeScript patterns for strict, type-safe, maintainable code in modern TypeScript and JavaScript applications. Covers strict compiler configuration, type design, narrowing, discriminated unions, generics, async and error handling, module boundaries, dependency hygiene, and type-level testing. Use when writing or reviewing TypeScript or JavaScript code.
工具 Tools调试工具通用访问网络待翻译
存储库
最近源活动
2026-11-20 09:13
检测 SKILL.md 语言
en
星标 ★
307,331
分支 Fork
45,351
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

TypeScript Development Patterns

TypeScript patterns and best practices for building robust, type-safe, and maintainable applications. The compiler is most useful when it can prove your program's shape, so the guiding principle here is: push the type system to do real work instead of fighting it. This skill is the "how." For the "what" and "when" (the decisions about which pattern to reach for), see the TypeScript rules — rules/typescript/coding-style.md and rules/typescript/patterns.md in this repository, installed as rules/ecc/typescript/coding-style.md and rules/ecc/typescript/patterns.md.

When to Activate

  • Writing new TypeScript or JavaScript code
  • Reviewing a PR that touches .ts or .tsx files
  • Refactoring existing TypeScript to remove any, tighten types, or add strictness
  • Designing types, generics, or module boundaries for a new feature
  • Setting up a new TypeScript project or upgrading tsconfig.json
  • Debugging type errors that cascade through a codebase (usually a design problem, not an annotation problem)

Core Principles

1. Strict Mode Is the Baseline

strict: true (which enables strictNullChecks, noImplicitAny, strictFunctionTypes, and the rest) is not optional in a healthy codebase. If a codebase cannot compile under strict, that is a migration task, not an excuse to leave the flag off.

// tsconfig.json — a strict, discriminating baseline
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "noFallthroughCasesInSwitch": true,
    "noPropertyAccessFromIndexSignature": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "forceConsistentCasingInFileNames": true,
    "verbatimModuleSyntax": true
  }
}

noUncheckedIndexedAccess makes array and record access possibly-undefined, which surfaces a whole class of runtime crashes at compile time. If it produces too much noise, this is the pattern to add, not the flag to remove:

// If you have proven the index exists, lift the element into a local first.
const [first] = items
if (first === undefined) {
  throw new Error("expected at least one item")
}

2. any Is a Bug, Not a Tool

any disables the type system exactly where a bug is most likely to hide: at the boundary with untrusted or dynamic data. Prefer unknown and narrow it. When you truly need a fallback, prefer an explicit loosening with a comment over a silent any.

// Bad: any disables checking on the public API
export function parseConfig(raw: any): Config {
  return raw.config ?? {}
}

interface Config {
  timeout: number
  retries: number
}

const DEFAULT_CONFIG: Config = { timeout: 30_000, retries: 3 }

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null
}

function toPositiveInt(value: unknown, field: string): number {
  if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
    throw new TypeError(`Expected ${field} to be a positive integer`)
  }
  return value
}

// Good: unknown forces safe narrowing at the edge. Every consumed field is
// validated with an explicit range, and defaults are declared up front.
export function parseConfig(raw: unknown): Config {
  if (!isRecord(raw)) return { ...DEFAULT_CONFIG }
  return {
    timeout: raw['timeout'] === undefined ? DEFAULT_CONFIG.timeout : toPositiveInt(raw['timeout'], 'timeout'),
    retries: raw['retries'] === undefined ? DEFAULT_CONFIG.retries : toPositiveInt(raw['retries'], 'retries'),
  }
}

3. Public APIs Get Explicit Types, Locals Get Inference

TypeScript infers local variables well. Exporting functions whose parameter and return types are implicit leaks inference decisions into every consumer and makes intent unreadable.

// Bad: exported API without explicit types
export function formatUser(user) {
  return `${user.firstName} ${user.lastName}`
}

// Good: explicit public contract, inferred internals
interface User {
  firstName: string
  lastName: string
}

export function formatUser(user: User): string {
  return `${user.firstName} ${user.lastName}`
}

Type Design

Interfaces vs. Type Aliases

interface for object shapes that may be extended or implemented; type for unions, intersections, tuples, mapped types, and utility types. Prefer string-literal unions over enum unless you need runtime value enumeration or interop with code that requires it.

interface User {
  id: string
  email: string
}

type UserRole = 'admin' | 'member'
type AdminUser = User & { role: 'admin' }

Discriminated Unions Are the Default State Machine

When a value can be in multiple shapes, model it as a discriminated union with a literal type/kind field. Exhaustive checking then becomes a free compiler feature: never a runtime fallback, always a compile error on a missing branch.

type Transaction =
  | { kind: 'draft'; id: string }
  | { kind: 'submitted'; id: string; submittedAt: Date }
  | { kind: 'paid'; id: string; paidAt: Date; amountCents: number }

function describe(t: Transaction): string {
  switch (t.kind) {
    case 'draft':
      return 'Saved but not sent'
    case 'submitted':
      return `Submitted on ${t.submittedAt.toISOString()}`
    case 'paid':
      return `Paid ${t.amountCents} cents on ${t.paidAt.toISOString()}`
    default:
      // exhaustive: any new member forces this to fail to compile
      return ass
评论
Aaffaan-m
affaan-m
affaan-m/ECC
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@affaan-m
所属大类工具 Tools / 调试工具
国内可用性通用
最近源活动2026-11-20 09:13
风险提示访问网络
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。