⚠️ Alpha内测版本警告:此为早期内部构建版本,尚不完整且可能存在错误,欢迎大家提Issue反馈问题或建议
Skip to content

0.4.3 给 JS 代码请个语法保镖——TypeScript 配置与最佳实践

一句话破题

TypeScript 让“运行时报错”变成“编译时报错”。用对 tsconfig.json,让类型系统成为你的守门员。

tsconfig.json 配置详解

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "baseUrl": "./",
    "paths": {
      "@src/*": ["src/*"],
      "@components/*": ["src/components/*"],
      "@lib/*": ["src/lib/*"]
    },
    "outDir": "dist"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist"]
}

严格模式配置

  • strict: 开启所有严格检查。
  • noImplicitAny: 禁止隐式 any;显式类型声明与推断结合。
  • noImplicitReturns: 函数必须在所有分支返回值。

模块解析与路径别名

  • baseUrl: 设定解析基准目录。
  • paths: 定义别名映射,减少相对路径。

示例:使用别名导入

ts
import { Button } from '@components/Button'
import { createClient } from '@lib/client'

type User = {
  id: string
  name: string
}

function getDisplayName(u: User): string {
  return u.name
}

类型声明文件管理

  • 社区类型:npm i -D @types/node @types/react @types/react-dom
  • 自定义声明:在 src/types/global.d.ts 中声明全局类型。
ts
declare global {
  interface EnvConfig {
    API_BASE: string
    ENV: 'development' | 'production' | 'test'
  }
}

export {}

AI 协作指南

  • 核心意图:让 AI 根据项目架构生成严格模式tsconfig.json别名方案
  • 需求定义公式:
    • “生成一个严格模式的 tsconfig.json,并为 src/components, src/lib 提供别名。”
  • 关键术语:strict, noImplicitAny, paths, declaration, @types

避坑指南

  • 禁止在代码中使用 any;如不确定类型,使用联合类型或 unknown 并显式收窄。
  • 别名与实际目录结构必须一致;路径映射的相对顺序会影响解析。
  • 更换构建工具时检查 modulemoduleResolution 的兼容性。