01. TypeScript 概述与环境搭建
·

01. TypeScript 概述与环境搭建
1. 什么是 TypeScript?
TypeScript 是微软开发的开源编程语言,是 JavaScript 的超集。它在 JavaScript 的基础上添加了静态类型系统,最终编译为纯 JavaScript 运行。
┌─────────────────────────────────────────────────────────────┐
│ TypeScript │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ JavaScript + 类型系统 │ │
│ │ • 静态类型检查 │ │
│ │ • 类与接口 │ │
│ │ • 泛型 │ │
│ │ • 装饰器 │ │
│ │ • 命名空间 │ │
│ └─────────────────────────────────────────────────────┘ │
│ ↓ 编译 │
│ 纯 JavaScript 代码 │
└─────────────────────────────────────────────────────────────┘
1.1 TypeScript vs JavaScript
| 特性 | JavaScript | TypeScript |
|---|---|---|
| 类型系统 | 动态类型 | 静态类型(可选) |
| 编译 | 解释执行 | 编译为 JS |
| 错误检测 | 运行时 | 编译时 |
| IDE 支持 | 基础 | 强大(智能提示、重构) |
| 学习曲线 | 平缓 | 中等 |
| 适用场景 | 小型项目 | 大型项目、团队协作 |
1.2 TypeScript 的核心优势
// JavaScript 的问题:运行时才发现错误
function add(a, b) {
return a + b;
}
add(1, '2'); // 返回 "12",不是预期结果,但不会报错
// TypeScript 的优势:编译时就能发现错误
function add(a: number, b: number): number {
return a + b;
}
// add(1, '2'); // ❌ 编译错误:类型不匹配
主要优势:
- 提前发现错误:在编写代码时就能发现类型错误
- 更好的 IDE 支持:自动补全、重构、导航
- 代码即文档:类型定义清晰表达意图
- 大型项目必备:团队协作更高效
2. 环境搭建
2.1 安装 Node.js
TypeScript 需要 Node.js 环境,访问 nodejs.org 下载安装。
# 验证安装
node --version # v18.x 或更高
npm --version # 9.x 或更高
2.2 安装 TypeScript
# 全局安装
npm install -g typescript
# 验证安装
tsc --version # Version 5.x
2.3 项目初始化
# 创建项目目录
mkdir my-ts-project
cd my-ts-project
# 初始化 npm 项目
npm init -y
# 安装 TypeScript 为开发依赖
npm install --save-dev typescript
# 生成 tsconfig.json 配置文件
tsc --init
3. 第一个 TypeScript 程序
3.1 创建源文件
// hello.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message = greet('TypeScript');
console.log(message);
3.2 编译运行
# 方式1:使用 tsc 命令直接编译
tsc hello.ts
# 方式2:使用 ts-node 直接运行(无需编译)
npx ts-node hello.ts
# 方式3:使用 node 运行编译后的文件
node hello.js
3.3 编译输出
// hello.js (编译后)
function greet(name) {
return "Hello, " + name + "!";
}
var message = greet('TypeScript');
console.log(message);
4. tsconfig.json 配置详解
4.1 基础配置
{
"compilerOptions": {
// 目标 ECMAScript 版本
"target": "ES2020",
// 模块系统
"module": "commonjs",
// 输出目录
"outDir": "./dist",
// 源码目录
"rootDir": "./src",
// 严格模式(推荐开启)
"strict": true,
// 生成 source map
"sourceMap": true,
// 移除注释
"removeComments": true,
// 不生成类型文件
"declaration": false
},
// 包含的文件
"include": ["src/**/*"],
// 排除的文件
"exclude": ["node_modules", "dist"]
}
4.2 常用编译选项
| 选项 | 说明 | 推荐值 |
|---|---|---|
target |
编译目标 JS 版本 | ES2020 或 ESNext |
module |
模块系统 | commonjs(Node)或 ESNext(前端) |
strict |
启用所有严格检查 | true |
outDir |
输出目录 | ./dist |
rootDir |
源码目录 | ./src |
esModuleInterop |
兼容 CommonJS 和 ES 模块 | true |
skipLibCheck |
跳过库类型检查 | true |
forceConsistentCasingInFileNames |
强制文件名大小写一致 | true |
4.3 严格模式家族
{
"compilerOptions": {
// 以下选项都可单独控制
"strict": true, // 全部开启
"noImplicitAny": true, // 禁止隐式 any
"strictNullChecks": true, // 严格 null 检查
"strictFunctionTypes": true, // 严格函数类型
"strictBindCallApply": true, // 严格 bind/call/apply
"strictPropertyInitialization": true, // 严格属性初始化
"noImplicitThis": true, // 禁止隐式 this
"useUnknownInCatchVariables": true // catch 变量类型为 unknown
}
}
5. 编辑器配置
5.1 VS Code 推荐配置
VS Code 对 TypeScript 有原生支持,推荐安装以下插件:
| 插件 | 用途 |
|---|---|
| TypeScript + JavaScript | 内置,无需安装 |
| Prettier | 代码格式化 |
| ESLint | 代码检查 |
5.2 .vscode/settings.json
{
"typescript.tsdk": "node_modules/typescript/lib",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"typescript.preferences.importModuleSpecifier": "relative"
}
6. 完整示例:搭建一个 TypeScript 项目
# 1. 创建项目结构
mkdir my-app
cd my-app
mkdir src
# 2. 初始化
npm init -y
npm install --save-dev typescript @types/node
# 3. 创建 tsconfig.json
npx tsc --init
# 4. 修改 tsconfig.json
# 设置 outDir: "./dist", rootDir: "./src"
# 5. 创建源码
# src/index.ts
# 6. 添加 npm scripts
# package.json 中添加:
# "build": "tsc",
# "start": "node dist/index.js",
# "dev": "ts-node src/index.ts"
# 7. 运行
npm run dev # 开发模式
npm run build # 构建
npm start # 运行构建产物
示例代码
// src/index.ts
interface Person {
name: string;
age: number;
}
function greet(person: Person): string {
return `Hello, ${person.name}! You are ${person.age} years old.`;
}
const user: Person = {
name: 'TypeScript',
age: 10
};
console.log(greet(user));
7. 常见问题
Q1: 安装 TypeScript 后 tsc 命令找不到?
# 使用 npx 运行
npx tsc --version
# 或重新安装
npm install -g typescript
Q2: 编译后出现 Cannot find module 错误?
# 安装 Node.js 类型定义
npm install --save-dev @types/node
Q3: 如何忽略 TypeScript 编译错误继续生成 JS?
tsc --noEmitOnError false
# 或在 tsconfig.json 中设置 "noEmitOnError": false
8. 总结
| 要点 | 说明 |
|---|---|
| TypeScript | JavaScript 超集,添加静态类型 |
| 安装 | npm install -g typescript |
| 编译 | tsc 命令 |
| 配置 | tsconfig.json |
| 运行 | ts-node 或编译后 node |
| VS Code | 原生支持 TypeScript |
更多推荐

所有评论(0)