Skip to content

代码规范

本页介绍项目的代码规范和最佳实践。

TypeScript

类型定义

typescript
// ✅ 好:明确的类型定义
interface Definition {
  id: string
  character: string
  content: string
}

// ❌ 不好:使用 any
const data: any = {}

函数

typescript
// ✅ 好:明确的参数和返回类型
function addDefinition(char: string, content: string): Definition {
  // ...
}

// ❌ 不好:缺少类型
function addDefinition(char, content) {
  // ...
}

React 组件

函数组件

typescript
// ✅ 推荐:函数组件 + Hooks
interface Props {
  title: string
  onSave: () => void
}

export function MyComponent({ title, onSave }: Props) {
  const [value, setValue] = useState('')
  
  return (
    <div>
      <h1>{title}</h1>
      <button onClick={onSave}>保存</button>
    </div>
  )
}

Props 定义

typescript
// Props 定义在组件文件顶部
interface SearchPageProps {
  initialQuery?: string
  onSearch: (query: string) => void
}

CSS Modules

命名

css
/* ✅ 好:使用 camelCase */
.searchInput { }
.submitButton { }

/* ❌ 不好:使用 kebab-case */
.search-input { }

使用

typescript
import styles from './SearchPage.module.css'

<input className={styles.searchInput} />

文件命名

类型命名方式示例
组件PascalCaseSearchPage.tsx
服务camelCaseexamGenerator.ts
工具camelCaseformatDate.ts
类型PascalCaseDefinition.ts
测试同源文件.teststorage.test.ts
样式同组件名.moduleSearchPage.module.css

目录结构

src/
├── components/          # 组件
│   ├── SearchPage.tsx
│   └── SearchPage.module.css
├── services/           # 服务
│   └── storage.ts
├── types/              # 类型
│   └── index.ts
└── utils/              # 工具
    └── format.ts

注释

typescript
/**
 * 生成练习题
 * @param config - 出题配置
 * @returns 生成的题目列表
 */
function generateExam(config: ExamConfig): Question[] {
  // 实现...
}

错误处理

typescript
// ✅ 好:明确的错误处理
try {
  const result = await fetchData()
  return result
} catch (error) {
  console.error('获取数据失败:', error)
  throw new Error('数据加载失败,请重试')
}

// ❌ 不好:忽略错误
try {
  const result = await fetchData()
} catch (e) {
  // 什么都不做
}

测试

typescript
describe('StorageService', () => {
  it('should add definition correctly', () => {
    const def = storage.addDefinition('之', '代词')
    
    expect(def.character).toBe('之')
    expect(def.content).toBe('代词')
    expect(def.id).toBeDefined()
  })
})

基于 MIT 许可发布