文档命令库TypeScript迁移

TypeScript迁移

将现有的 JavaScript 项目渐进式迁移到 TypeScript,提升代码质量和开发体验,同时保持项目的稳定性。

适用场景

  • JavaScript 项目需要类型安全
  • 大型项目重构和维护优化
  • 团队协作中减少类型相关错误
  • 准备升级现代化技术栈

复制命令

# 基础迁移命令
将当前JavaScript项目迁移到TypeScript
 
# 渐进式迁移
逐步将 src/components 目录下的文件迁移到TypeScript
 
# 包含配置优化
迁移到TypeScript并设置严格的类型检查配置
 
# 特定文件迁移
 src/utils/api.js 迁移到TypeScript并添加完整类型定义

执行步骤

1. 项目准备和配置设置

Claude Code 会自动:

  • 安装 TypeScript 相关依赖
  • 创建或优化 tsconfig.json 配置
  • 设置编译器选项和路径映射
  • 配置开发工具和构建流程
{
  "compilerOptions": {
    "target": "ES2020",
    "lib": ["dom", "dom.iterable", "ES2020"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

2. 依赖包类型定义安装

# 自动安装常用类型定义包
npm install -D @types/node @types/react @types/react-dom
npm install -D typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin

3. 文件逐步迁移

Claude Code 会按优先级迁移:

第一步:工具类和纯函数

// 迁移前:utils/helper.js
export function calculateTotal(amount, tax) {
  return amount * (1 + tax);
}
 
// 迁移后:utils/helper.ts
export function calculateTotal(amount: number, tax: number): number {
  if (amount < 0 || tax < 0) {
    throw new Error('Amount and tax must be non-negative');
  }
  return amount * (1 + tax);
}

第二步:接口和类型定义

// types/api.ts
export interface User {
  id: number;
  name: string;
  email: string;
  avatar?: string;
}
 
export interface ApiResponse<T> {
  data: T;
  status: 'success' | 'error';
  message?: string;
}

第三步:React组件迁移

// 迁移前:components/Button.jsx
export default function Button({ children, onClick, disabled }) {
  return (
    <button onClick={onClick} disabled={disabled}>
      {children}
    </button>
  );
}
 
// 迁移后:components/Button.tsx
import React from 'react';
 
interface ButtonProps {
  children: React.ReactNode;
  onClick?: () => void;
  disabled?: boolean;
  variant?: 'primary' | 'secondary';
}
 
export default function Button({ 
  children, 
  onClick, 
  disabled = false,
  variant = 'primary'
}: ButtonProps) {
  return (
    <button 
      className={`btn btn--${variant}`}
      onClick={onClick} 
      disabled={disabled}
    >
      {children}
    </button>
  );
}

4. 构建和验证

# TypeScript 类型检查
npx tsc --noEmit
 
# 运行测试确保功能正常
npm test
 
# 检查 ESLint 配置
npm run lint

验证命令

# 类型检查
npx tsc --noEmit --strict
 
# 构建项目
npm run build
 
# 运行所有测试
npm test
 
# 检查代码质量
npm run lint

迁移策略

渐进式迁移路径

  1. 配置设置(第1周)

    • 安装TypeScript和相关工具
    • 配置tsconfig.json和构建流程
    • 设置开发环境支持
  2. 基础迁移(第2-3周)

    • 迁移工具函数和常量
    • 添加基础类型定义
    • 更新导入/导出语句
  3. 组件迁移(第4-6周)

    • 迁移React组件和Props类型
    • 添加事件处理器类型
    • 处理状态管理类型
  4. 高级功能(第7-8周)

    • 泛型和高级类型
    • API接口类型定义
    • 第三方库集成

类型定义优先级

高优先级

  • API 响应和请求类型
  • 核心业务数据模型
  • 组件 Props 接口
  • 状态管理类型

中优先级

  • 工具函数参数类型
  • 事件处理器类型
  • 配置对象接口

低优先级

  • 内部辅助类型
  • 复杂泛型定义
  • 装饰器类型

💡 渐进策略:启用 allowJs: true 选项,让 TypeScript 和 JavaScript 文件共存,逐步迁移而不破坏现有功能。

常见问题处理

第三方库类型缺失

// 临时类型声明文件:types/vendor.d.ts
declare module 'some-untyped-library' {
  export function someFunction(param: string): Promise<any>;
}

复杂类型推断

// 使用工具类型简化复杂定义
type UserFormData = Pick<User, 'name' | 'email'>;
type UpdateUser = Partial<User> & { id: number };

严格模式配置

// 逐步启用严格检查
{
  "compilerOptions": {
    "strict": false,
    "noImplicitAny": true,
    "strictNullChecks": false,
    // 逐步启用其他严格选项
  }
}

风险提示与回滚

潜在风险

  • 类型定义错误可能导致运行时问题
  • 构建时间可能增加
  • 第三方库类型兼容性问题

回滚方案

# 保留 JavaScript 版本的备份分支
git checkout -b backup-before-typescript
 
# 如需回滚,移除TypeScript配置
rm tsconfig.json
npm uninstall typescript @types/*
 
# 将所有 .ts/.tsx 文件重命名为 .js/.jsx
find src -name "*.ts" -exec mv {} {}x \;
find src -name "*.tsx" -exec mv {} {}x \;

性能优化建议

  • 使用 skipLibCheck: true 加速编译
  • 配置增量编译 incremental: true
  • 合理使用 any 类型作为迁移过渡
  • 利用 TypeScript 的工程化能力优化开发体验

相关卡片

参考来源

关于我