Skip to content

TypeScript 规范

核心原则

TypeScript 必须启用严格模式,使用明确的类型定义,避免使用 any 类型。

允许的做法

类型定义

typescript
// ✅ 正确 - interface
interface User {
  id: number;
  name: string;
  email: string;
}

// ✅ 正确 - type
type Status = 'pending' | 'active' | 'inactive';
type Result<T> = { success: true; data: T } | { success: false; errorMessage: string };

// ✅ 正确 - 函数类型
function getUser(id: number): Promise<User> {
  return fetch(`/api/users/${id}`).then(res => res.json());
}

泛型使用

typescript
// ✅ 正确 - 泛型函数
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

// ✅ 正确 - 泛型约束
interface HasId {
  id: number;
}

function findById<T extends HasId>(items: T[], id: number): T | undefined {
  return items.find(item => item.id === id);
}

类型守卫

typescript
// ✅ 正确
function isUser(obj: unknown): obj is User {
  return (
    typeof obj === 'object' &&
    obj !== null &&
    'id' in obj &&
    'name' in obj
  );
}

工具类型

typescript
// ✅ 正确
type PartialUser = Partial<User>;
type UserKeys = keyof User;
type UserName = Pick<User, 'name'>;
type UserWithoutId = Omit<User, 'id'>;

禁止的做法

  • 禁止 使用 any
  • 避免 强制类型转换
typescript
// ❌ 错误
function process(data: any) {  // 避免 any
  return data;
}

// ✅ 正确
function process(data: unknown) {
  if (isUser(data)) {
    return data.name;
  }
}

tsconfig.json 配置

Vite 项目配置

json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",

    /* Linting */
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,

    /* Path aliases */
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

tsconfig.node.json(Vite 配置文件用)

json
{
  "compilerOptions": {
    "composite": true,
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "include": ["vite.config.ts"]
}

特殊场景

API 响应类型

typescript
// ✅ 正确
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  errorMessage?: string;
  errorCode?: number;
}

interface PagedResponse<T> extends ApiResponse<T[]> {
  total: number;
  current: number;
  pageSize: number;
}

相关文档