AgentSkillsCN

typescript-patterns

TypeScript的模式——严格类型、泛型、依赖注入、异步模式、并发编程。适用于编写TypeScript代码的场景。

SKILL.md
--- frontmatter
name: typescript-patterns
description: TypeScript patterns - strict types, generics, DI, async patterns, concurrency. Use when writing TypeScript.

TypeScript Patterns

Type Safety

  • No any - Ask user first. Offer: generic, interface, or discriminated union
  • unknown requires type guard - function isX(v: unknown): v is X
  • Generics over loose types - function first<T>(items: T[]): T | undefined
  • Branded types for IDs - type UserId = string & { readonly __brand: 'UserId' }

Architecture

  • No hardcoding - Use config, environment, or injection
  • Single responsibility - One purpose per function/class
  • Dependency injection - Inject interfaces, not implementations
  • Event-driven decoupling - TypedEventEmitter for cross-cutting concerns

Async Patterns

NeedPattern
Multiple independent fetchesPromise.all([...])
Partial failure handlingPromise.allSettled([...])
First response wins / timeoutPromise.race([...])
Streaming / paginationasync function* generator()
Cancelable operationsAbortController + signal
Concurrency limitingSemaphore or mapWithLimit
Shared state protectionMutex
Retry with backoffretry(fn, { attempts, delay, backoff })

See reference files for implementations.

References

Checklist

  • any? → Generic or interface
  • unknown? → Type guard
  • Hardcoded value? → Config or inject
  • Multiple responsibilities? → Split
  • Hard import? → Inject interface
  • Decoupling needed? → EventEmitter
  • Streaming/pagination? → AsyncGenerator
  • Cancelable? → AbortController
  • Multiple fetches? → Promise.all or allSettled
  • Need fallback/timeout? → Promise.race
  • Shared state? → Mutex
  • Too many parallel ops? → Semaphore