强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

TypeScript 开发指南 / 02 - 安装与配置

安装与配置

环境准备

前置条件

在安装 TypeScript 之前,需要确保已安装 Node.js(推荐 v18+):

# 检查 Node.js 版本
node --version   # 应输出 v18.x.x 或更高

# 检查 npm 版本
npm --version    # 应输出 9.x.x 或更高

安装 TypeScript

全局安装

# 使用 npm 全局安装
npm install -g typescript

# 或使用 yarn
yarn global add typescript

# 或使用 pnpm
pnpm add -g typescript

# 验证安装
tsc --version
# 输出:Version 5.x.x

项目本地安装(推荐)

# 初始化项目
mkdir my-ts-project && cd my-ts-project
npm init -y

# 作为开发依赖安装
npm install -D typescript

# 通过 npx 运行
npx tsc --version

注意:推荐使用项目本地安装,这样不同项目可以使用不同版本的 TypeScript,避免版本冲突。

包管理器对比

包管理器安装命令锁文件推荐度
npmnpm install -D typescriptpackage-lock.json⭐⭐⭐
yarnyarn add -D typescriptyarn.lock⭐⭐⭐
pnpmpnpm add -D typescriptpnpm-lock.yaml⭐⭐⭐⭐
bunbun add -d typescriptbun.lockb⭐⭐⭐

tsc 编译器

tsc(TypeScript Compiler)是 TypeScript 的核心工具。

基本用法

# 编译单个文件
tsc app.ts

# 编译多个文件
tsc app.ts utils.ts

# 使用配置文件编译(默认读取 tsconfig.json)
tsc

# 监听模式(文件变更时自动编译)
tsc --watch
# 或简写
tsc -w

常用命令行选项

# 指定输出目录
tsc --outDir dist

# 指定目标 ES 版本
tsc --target ES2022

# 启用严格模式
tsc --strict

# 指定模块系统
tsc --module ESNext

# 仅做类型检查,不输出文件
tsc --noEmit

# 显示所有编译选项
tsc --help

编译选项速查表

选项说明默认值
--target编译目标 ES 版本ES2016
--module模块系统CommonJS(Node16 时为 Node16)
--outDir输出目录与源文件同目录
--rootDir源文件根目录自动推断
--strict启用所有严格检查false
--noEmit不输出编译文件false
--declaration生成 .d.ts 声明文件false
--sourceMap生成 Source Mapfalse
--esModuleInteropESM/CJS 互操作false
--skipLibCheck跳过 .d.ts 文件检查false

tsconfig.json

tsconfig.json 是 TypeScript 项目的配置文件,定义了编译选项和项目结构。

生成配置文件

# 生成默认的 tsconfig.json
tsc --init

完整配置示例

{
  "compilerOptions": {
    /* 语言和环境 */
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "jsx": "react-jsx",

    /* 模块系统 */
    "module": "ESNext",
    "moduleResolution": "bundler",
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },

    /* 输出 */
    "outDir": "./dist",
    "rootDir": "./src",
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,

    /* 严格检查 */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,

    /* 互操作 */
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,

    /* 性能 */
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

关键配置项详解

target(编译目标)

指定 TypeScript 编译输出的 ECMAScript 版本:

// target: "ES5" 时
// 解构赋值会被编译为兼容代码
const { name, age } = user;
// ↓ 编译后
// var name = user.name;
// var age = user.age;

// target: "ES2022" 时
// 解构赋值保持原样
const { name, age } = user;
target 值特性支持适用场景
ES5兼容 IE11遗留项目
ES2015/ES6let/const, 箭头函数, Promise广泛兼容
ES2020Optional chaining, BigInt现代浏览器
ES2022Top-level await, Array.at()最新环境
ESNext所有最新特性前沿项目

strict(严格模式)

strict: true 会开启以下所有严格检查:

选项说明
strictNullChecksnullundefined 是独立类型
strictFunctionTypes函数参数类型严格检查
strictBindCallApplybind/call/apply 参数检查
strictPropertyInitialization类属性必须初始化
noImplicitAny禁止隐式 any 类型
noImplicitThis禁止隐式 this 类型
alwaysStrict输出文件包含 "use strict"
// strictNullChecks: false(默认)
const element = document.getElementById("app"); // HTMLElement | null
element.innerHTML = "Hello"; // ✅ 不报错,但运行时可能为 null

// strictNullChecks: true
const element = document.getElementById("app"); // HTMLElement | null
element.innerHTML = "Hello"; // ❌ 编译错误:element 可能为 null
if (element) {
  element.innerHTML = "Hello"; // ✅ 类型收窄后安全
}

moduleResolution(模块解析策略)

策略说明适用场景
nodeNode.js 传统解析(CJS)CommonJS 项目
node16Node.js 16+ 解析(CJS + ESM)Node.js 16+ 项目
bundler打包器解析策略Vite/esbuild/Webpack 项目
nodenextNode.js 最新解析Node.js 最新项目

项目引用

对于大型项目,可以使用项目引用(Project References)将代码拆分为多个子项目:

// tsconfig.json(根配置)
{
  "files": [],
  "references": [
    { "path": "./packages/core" },
    { "path": "./packages/utils" },
    { "path": "./packages/app" }
  ]
}
// packages/core/tsconfig.json
{
  "compilerOptions": {
    "composite": true,
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src/**/*"]
}
# 构建所有项目
tsc --build

# 增量构建
tsc --build --incremental

IDE 支持

VS Code(推荐)

VS Code 内置了 TypeScript 支持,无需额外安装插件。

核心功能:

  • 智能代码补全
  • 实时类型检查(红色波浪线提示)
  • 重构工具(重命名、提取函数等)
  • 跳转到定义
  • 查找所有引用

推荐插件:

插件功能
ESLint代码规范检查
Prettier代码格式化
Error Lens行内显示错误信息
TypeScript Hero自动管理 import

VS Code 设置推荐:

// .vscode/settings.json
{
  "typescript.tsdk": "node_modules/typescript/lib",
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  }
}

WebStorm / IntelliJ IDEA

JetBrains 系 IDE 内置 TypeScript 支持:

  1. 打开 Settings → Languages & Frameworks → TypeScript
  2. 设置 TypeScript 版本为项目本地版本
  3. 启用 Recompile on changes

其他编辑器

编辑器TypeScript 支持
Sublime Text通过 LSP 插件支持
Vim / Neovim通过 coc.nvim 或内置 LSP 支持
Emacs通过 tide 或 eglot 支持

项目结构最佳实践

my-ts-project/
├── src/                    # 源代码目录
│   ├── index.ts           # 入口文件
│   ├── utils/             # 工具函数
│   │   └── helpers.ts
│   └── types/             # 类型定义
│       └── index.ts
├── dist/                  # 编译输出目录
├── tests/                 # 测试文件
├── tsconfig.json          # TypeScript 配置
├── package.json           # 项目配置
├── .eslintrc.json         # ESLint 配置
└── .gitignore             # Git 忽略规则

.gitignore 推荐配置:

node_modules/
dist/
*.js
*.js.map
*.d.ts
!tsconfig.json

常见问题

Q: tscts-node 有什么区别?

工具用途输出
tsc编译 TypeScript 为 JavaScript生成 .js 文件
ts-node直接运行 TypeScript 文件不生成文件(内存编译)

Q: 如何在已有 JavaScript 项目中添加 TypeScript?

# 1. 安装 TypeScript
npm install -D typescript

# 2. 生成 tsconfig.json
npx tsc --init

# 3. 将 .js 文件逐步重命名为 .ts
mv src/app.js src/app.ts

Q: allowJscheckJs 有什么区别?

{
  "compilerOptions": {
    "allowJs": true,  // 允许编译 JavaScript 文件
    "checkJs": true   // 对 JavaScript 文件也进行类型检查
  }
}

业务场景:企业级项目配置

以下是一个适合企业级 React + TypeScript 项目的配置模板:

{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "bundler",
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"],
      "@utils/*": ["src/utils/*"],
      "@hooks/*": ["src/hooks/*"],
      "@types/*": ["src/types/*"]
    }
  },
  "include": ["src/**/*", "vite-env.d.ts"],
  "exclude": ["node_modules", "dist"]
}

扩展阅读