typescript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Code Style Guide
TypeScript代码风格指南
Types and Type Safety
类型与类型安全
- Avoid explicit type annotations when TypeScript can infer
- Avoid implicitly ; explicitly type when necessary
any - Use accurate types: prefer over
Record<PropertyKey, unknown>orobjectany - Prefer for object shapes (e.g., React props); use
interfacefor unions/intersectionstype - Prefer over plain
as const satisfies XyzInterfaceas const - Prefer over
@ts-expect-errorover@ts-ignoreas any - Avoid meaningless null/undefined parameters; design strict function contracts
- 当TypeScript可以自动推断类型时,避免显式添加类型注解
- 避免隐式类型;必要时显式声明类型
any - 使用精确类型:优先选择而非
Record<PropertyKey, unknown>或objectany - 定义对象结构时优先使用(例如React props);联合/交叉类型使用
interfacetype - 优先选择而非单纯的
as const satisfies XyzInterfaceas const - 优先使用,其次是
@ts-expect-error,避免使用@ts-ignoreas any - 避免无意义的null/undefined参数;设计严格的函数契约
Async Patterns
异步模式
- Prefer /
asyncover callbacks orawaitchains.then() - Prefer async APIs over sync ones (avoid )
*Sync - Use promise-based variants:
import { readFile } from 'fs/promises' - Use ,
Promise.allfor concurrent operations where safePromise.race
- 优先使用/
async而非回调函数或await链式调用.then() - 优先选择异步API而非同步API(避免使用类方法)
*Sync - 使用基于Promise的变体:
import { readFile } from 'fs/promises' - 在安全场景下,使用、
Promise.all处理并发操作Promise.race
Code Structure
代码结构
- Prefer object destructuring
- Use consistent, descriptive naming; avoid obscure abbreviations
- Replace magic numbers/strings with well-named constants
- Defer formatting to tooling
- 优先使用对象解构
- 使用一致且具有描述性的命名;避免模糊的缩写
- 使用命名常量替代魔法数字/字符串
- 代码格式化交由工具处理
UI and Theming
UI与主题
- Use , Ant Design components instead of raw HTML tags
@lobehub/ui - Design for dark mode and mobile responsiveness
- Use token system instead of hard-coded colors
antd-style
- 使用、Ant Design组件而非原生HTML标签
@lobehub/ui - 适配暗黑模式与移动端响应式设计
- 使用令牌系统而非硬编码颜色
antd-style
Performance
性能优化
- Prefer loops over index-based
for…ofloopsfor - Reuse existing utils in or installed npm packages
packages/utils - Query only required columns from database
- 优先选择循环而非基于索引的
for…of循环for - 复用中已有的工具函数或已安装的npm包工具
packages/utils - 仅从数据库查询所需的列
Time Consistency
时间一致性
- Assign to a constant once and reuse for consistency
Date.now()
- 先将赋值给一个常量,然后复用该常量以保证一致性
Date.now()
Logging
日志规范
- Never log user private information (API keys, etc.)
- Don't use directly (logs to console)
import { log } from 'debug' - Use in catch blocks instead of debug package
console.error
- 切勿记录用户隐私信息(如API密钥等)
- 不要直接使用(会输出到控制台)
import { log } from 'debug' - 在catch块中使用而非debug包
console.error