typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Guidelines

TypeScript开发指南

Standards and best practices for TypeScript development with modern tooling. Follow these guidelines when writing or modifying TypeScript code.
搭配现代工具链的TypeScript开发标准与最佳实践。编写或修改TypeScript代码时请遵循以下指南。

Design Principles

设计原则

Apply DRY, KISS, and SOLID consistently. Prefer functional approaches where relevant; use classes for stateful behavior. Use composition over inheritance. Each module should have a single responsibility. Use dependency injection for class dependencies.
始终遵循DRY、KISS和SOLID原则。在合适的场景下优先采用函数式编程方式;使用类来实现有状态的行为。优先使用组合而非继承。每个模块应具备单一职责。对类的依赖项使用依赖注入。

Code Style

代码风格

  • Naming: Descriptive yet concise names for variables, functions, and classes
  • Documentation: JSDoc comments for public APIs, complex logic, and non-obvious design decisions
  • Type annotations: Be explicit with typing to reduce inference time; avoid
    any
    unless necessary
  • Imports: Avoid barrel exports to prevent circular dependencies; prefer direct imports
  • 命名规范:变量、函数和类使用描述性且简洁的名称
  • 文档注释:公共API、复杂逻辑和非直观的设计决策需添加JSDoc注释
  • 类型注解:显式添加类型注解以减少类型推断时间;除非必要,避免使用
    any
    类型
  • 导入规则:避免桶式导出(barrel exports)以防止循环依赖;优先使用直接导入

Type Safety

类型安全

  • Strict TypeScript: Use strict mode with proper type definitions. Use type-safe patterns like Zod schemas for validation and type-safe DOM helpers where applicable.
  • Avoid
    any
    : Use
    unknown
    instead of
    any
    when the type is truly unknown. Narrow types appropriately.
  • Type inference: Be explicit with typing to reduce inference time and improve clarity
  • 严格TypeScript模式:启用严格模式并使用正确的类型定义。适用时使用类型安全的模式,例如用Zod Schema进行验证,以及类型安全的DOM辅助工具。
  • 避免
    any
    :当类型确实未知时,使用
    unknown
    而非
    any
    。适当缩小类型范围。
  • 类型推断:显式添加类型注解以减少推断时间并提升代码清晰度

Type Patterns

类型模式

  • Union types: Use union types for values that can be one of several types
  • Discriminated unions: Use discriminated unions for type-safe state machines
  • Generic constraints: Use generic constraints to ensure type safety
  • Utility types: Leverage TypeScript utility types (Pick, Omit, Partial, etc.)
  • 联合类型:为可能属于多种类型之一的值使用联合类型
  • 可辨识联合:为类型安全的状态机使用可辨识联合
  • 泛型约束:使用泛型约束确保类型安全
  • 工具类型:充分利用TypeScript工具类型(Pick、Omit、Partial等)

Architecture

架构

Module Organization

模块组织

  • Each module focuses on one concern with clear boundaries
  • Extract reusable functions to avoid duplication
  • Design for reusability across contexts
  • Co-locate types with their usage or in dedicated type files
  • Keep types at appropriate module boundaries
  • 每个模块聚焦单一关注点,边界清晰
  • 提取可复用函数以避免代码重复
  • 设计时考虑跨场景复用性
  • 将类型定义与使用代码放在一起,或存放在专门的类型文件中
  • 在合适的模块边界处定义类型

Dependency Management

依赖管理

  • Use dependency injection for testability
  • Prefer composition over inheritance
  • Keep dependencies minimal and focused
  • 使用依赖注入提升可测试性
  • 优先使用组合而非继承
  • 保持依赖项精简且聚焦

Testing

测试

Structure

结构

  • Tests mirror
    src/
    directory structure
  • Test files:
    *.test.ts
    or
    *.spec.ts
  • Use descriptive test names
  • Always check for appropriate unit tests when changing code
  • 测试文件镜像
    src/
    目录结构
  • 测试文件命名:
    *.test.ts
    *.spec.ts
  • 使用描述性的测试名称
  • 修改代码时务必检查是否有对应的单元测试

Quality

质量

  • Use AAA (Arrange, Act, Assert) pattern
  • Tests should be useful, readable, concise, maintainable
  • Test edge cases and error conditions
  • Maintain test coverage for critical paths
  • 使用AAA(Arrange、Act、Assert)模式
  • 测试用例应实用、可读、简洁且易于维护
  • 测试边界情况和错误场景
  • 确保关键路径的测试覆盖率

Tools

工具

  • Vitest: Use Vitest for unit and integration tests (preferred over Jest)
  • Use
    @vitest/coverage-v8
    for coverage
  • Use
    jsdom
    for DOM testing when needed
  • Mock external dependencies appropriately
  • Playwright: Use Playwright for end-to-end (E2E) tests
  • Vitest:使用Vitest进行单元测试和集成测试(优先于Jest)
  • 使用
    @vitest/coverage-v8
    生成测试覆盖率报告
  • 必要时使用
    jsdom
    进行DOM测试
  • 合理模拟外部依赖
  • Playwright:使用Playwright进行端到端(E2E)测试

Code Formatting and Linting

代码格式化与Lint检查

Prettier

Prettier

  • Use Prettier for consistent code formatting
  • Config:
    printWidth: 120
    ,
    singleQuote: true
    ,
    jsxSingleQuote: true
  • Run
    pnpm format
    to format code
  • Run
    pnpm format:check
    to check formatting
  • 使用Prettier保证代码格式一致
  • 配置:
    printWidth: 120
    ,
    singleQuote: true
    ,
    jsxSingleQuote: true
  • 运行
    pnpm format
    格式化代码
  • 运行
    pnpm format:check
    检查代码格式

ESLint

ESLint

  • Use ESLint with TypeScript plugin
  • Use
    @typescript-eslint/parser
    and
    @typescript-eslint/eslint-plugin
  • Run
    pnpm lint
    to check linting
  • Run
    pnpm lint:fix
    to auto-fix issues
  • 使用搭配TypeScript插件的ESLint
  • 使用
    @typescript-eslint/parser
    @typescript-eslint/eslint-plugin
  • 运行
    pnpm lint
    检查代码规范
  • 运行
    pnpm lint:fix
    自动修复问题

Framework Recommendations

框架推荐

For Non-Heavy Client Interaction

低客户端交互场景

  • Astro: Excellent choice for content-focused sites, blogs, documentation
    • Minimal JavaScript by default
    • Static generation with server islands when needed
    • Great performance and SEO
    • TypeScript-first with excellent DX
  • Astro:内容型网站、博客、文档站点的绝佳选择
    • 默认仅加载最少的JavaScript
    • 静态生成,必要时可使用服务端孤岛(server islands)
    • 性能优异,SEO友好
    • 原生支持TypeScript,开发者体验出色

For Heavy Client Interaction

高客户端交互场景

  • React, Svelte, or SolidJS with TypeScript
  • Choose based on team preference and project requirements
  • React、Svelte或SolidJS搭配TypeScript
  • 根据团队偏好和项目需求选择

Build Tools

构建工具

  • Vite: Preferred build tool for development and production (unless directed otherwise)
  • Modern Rust-based tooling: Prefer Rolldown or other lower-level language tooling
    • Avoid Webpack and other older JavaScript-based bundlers unless specifically required
  • Vite:开发和生产环境的首选构建工具(除非有特殊要求)
  • 基于Rust的现代工具链:优先选择Rolldown或其他底层语言开发的工具
    • 除非特别需要,否则避免使用Webpack等较旧的JavaScript打包工具

Package Management

包管理

  • pnpm: Preferred package manager (faster, more efficient than npm/yarn)
  • Use
    packageManager
    field in package.json
  • Use pnpm workspaces for monorepos
  • pnpm:首选包管理器(比npm/yarn更快、更高效)
  • 在package.json中添加
    packageManager
    字段
  • 对单体仓库(monorepo)使用pnpm workspaces

Implementation

实现规范

When implementing TypeScript code:
  • Ensure code passes type checking before committing
  • Group related changes with tests in atomic commits
  • Check for existing workflow patterns (spec-first, TDD, etc.) and follow them
在编写TypeScript代码时:
  • 提交代码前确保通过类型检查
  • 将相关修改与测试用例放在原子提交中
  • 遵循现有的工作流模式(如先写规格、测试驱动开发等)

References

参考资料

For monorepo-specific patterns using pnpm, see
references/pnpm-monorepo.md
.
关于使用pnpm的单体仓库特定模式,请参阅
references/pnpm-monorepo.md