1.1 TypeScript概述
1.1.1 什么是TypeScript
TypeScript是由Microsoft开发的开源编程语言,它是JavaScript的超集,为JavaScript添加了可选的静态类型检查和其他企业级开发特性。TypeScript代码最终会被编译成纯JavaScript代码,可以在任何支持JavaScript的环境中运行。
1.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"); // 编译时错误:类型不匹配
现代JavaScript特性支持
// ES6+ 特性
class Person {
constructor(private name: string, private age: number) {}
greet(): string {
return `Hello, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
// 箭头函数
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// 解构赋值
const { name, age } = new Person("Alice", 30);
强大的IDE支持
- 智能代码补全
- 实时错误检查
- 重构支持
- 导航和搜索
1.1.3 TypeScript vs JavaScript
特性 | JavaScript | TypeScript |
---|---|---|
类型检查 | 运行时 | 编译时 |
错误发现 | 运行时 | 开发时 |
IDE支持 | 基础 | 强大 |
学习曲线 | 平缓 | 稍陡 |
编译步骤 | 无 | 需要 |
文件大小 | 小 | 稍大(开发时) |
1.1.4 TypeScript的优势
1. 提高代码质量
// 类型安全
interface User {
id: number;
name: string;
email: string;
}
function getUserById(id: number): User | null {
// 实现逻辑
return null;
}
// 编译器会检查返回值的使用
const user = getUserById(1);
if (user) {
console.log(user.name); // 安全访问
}
2. 更好的开发体验
// 智能提示和自动补全
class Calculator {
add(a: number, b: number): number {
return a + b;
}
multiply(a: number, b: number): number {
return a * b;
}
}
const calc = new Calculator();
calc. // IDE会显示可用方法
3. 重构支持
// 重命名变量或方法时,所有引用都会自动更新
class UserService {
private users: User[] = [];
// 重命名这个方法
findUserByEmail(email: string): User | undefined {
return this.users.find(user => user.email === email);
}
}
1.1.5 TypeScript的应用场景
大型项目开发
- 企业级应用
- 多人协作项目
- 长期维护的项目
库和框架开发
- React组件库
- Node.js模块
- 工具库开发
现代前端框架
- Angular(原生支持)
- React(官方推荐)
- Vue.js(3.0+原生支持)
1.2 环境搭建
1.2.1 安装Node.js
Windows安装
- 访问 Node.js官网
- 下载LTS版本
- 运行安装程序
- 验证安装:
bash node --version npm --version
#### macOS安装bash # 使用Homebrew brew install node # 或者使用官方安装包 # 从官网下载.pkg文件并安装
Linux安装
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# CentOS/RHEL
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
# 使用包管理器
sudo apt update
sudo apt install nodejs npm
1.2.2 安装TypeScript
全局安装
# 使用npm
npm install -g typescript
# 使用yarn
yarn global add typescript
# 验证安装
tsc --version
项目本地安装
# 初始化项目
mkdir my-typescript-project
cd my-typescript-project
npm init -y
# 安装TypeScript作为开发依赖
npm install --save-dev typescript
npm install --save-dev @types/node
# 创建TypeScript配置文件
npx tsc --init
1.2.3 开发工具配置
Visual Studio Code
安装VS Code 1. 访问 VS Code官网 2. 下载对应平台的安装包 3. 安装并启动
推荐扩展
{
"recommendations": [
"ms-vscode.vscode-typescript-next",
"esbenp.prettier-vscode",
"ms-vscode.vscode-eslint",
"bradlc.vscode-tailwindcss",
"ms-vscode.vscode-json",
"formulahendry.auto-rename-tag",
"christian-kohler.path-intellisense"
]
}
VS Code配置
// .vscode/settings.json
{
"typescript.preferences.quoteStyle": "single",
"typescript.updateImportsOnFileMove.enabled": "always",
"typescript.suggest.autoImports": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
WebStorm/IntelliJ IDEA
配置TypeScript 1. File → Settings → Languages & Frameworks → TypeScript 2. 启用TypeScript Language Service 3. 配置TypeScript编译器路径
其他编辑器
Vim/Neovim
" 使用coc.nvim
Plug 'neoclide/coc.nvim', {'branch': 'release'}
" 安装TypeScript支持
:CocInstall coc-tsserver
Sublime Text
# 安装Package Control后
# 安装TypeScript插件
Ctrl+Shift+P → Package Control: Install Package → TypeScript
1.2.4 项目初始化
创建基础项目结构
mkdir typescript-learning
cd typescript-learning
# 初始化npm项目
npm init -y
# 安装依赖
npm install --save-dev typescript @types/node
npm install --save-dev ts-node nodemon
npm install --save-dev prettier eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
# 创建目录结构
mkdir src
mkdir dist
mkdir tests
配置TypeScript
# 生成tsconfig.json
npx tsc --init
tsconfig.json配置
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"removeComments": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "tests"]
}
配置package.json脚本
{
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts",
"watch": "nodemon --exec ts-node src/index.ts",
"clean": "rm -rf dist",
"type-check": "tsc --noEmit",
"lint": "eslint src/**/*.ts",
"format": "prettier --write src/**/*.ts"
}
}
ESLint配置
// .eslintrc.json
{
"parser": "@typescript-eslint/parser",
"extends": [
"eslint:recommended",
"@typescript-eslint/recommended"
],
"plugins": ["@typescript-eslint"],
"env": {
"node": true,
"es6": true
},
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-function-return-type": "warn",
"@typescript-eslint/no-explicit-any": "warn"
}
}
Prettier配置
// .prettierrc
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false
}
1.2.5 第一个TypeScript程序
创建入口文件
// src/index.ts
interface Person {
name: string;
age: number;
email?: string;
}
class Greeter {
private greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(person: Person): string {
return `${this.greeting}, ${person.name}! You are ${person.age} years old.`;
}
}
function main(): void {
const person: Person = {
name: 'Alice',
age: 30,
email: 'alice@example.com'
};
const greeter = new Greeter('Hello');
const message = greeter.greet(person);
console.log(message);
console.log('TypeScript is working!');
}
// 运行主函数
main();
编译和运行
# 编译TypeScript
npm run build
# 运行编译后的JavaScript
npm start
# 或者直接运行TypeScript(开发模式)
npm run dev
# 监听文件变化自动重启
npm run watch
1.2.6 调试配置
VS Code调试配置
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug TypeScript",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.ts",
"runtimeArgs": ["-r", "ts-node/register"],
"env": {
"NODE_ENV": "development"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"]
},
{
"name": "Debug Compiled JS",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/dist/index.js",
"preLaunchTask": "npm: build",
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"console": "integratedTerminal"
}
]
}
任务配置
// .vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "npm: build",
"type": "npm",
"script": "build",
"group": "build",
"presentation": {
"panel": "shared",
"showReuseMessage": false,
"clear": true
},
"problemMatcher": "$tsc"
},
{
"label": "npm: watch",
"type": "npm",
"script": "watch",
"isBackground": true,
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"panel": "dedicated",
"reveal": "never"
}
}
]
}
1.3 TypeScript编译器详解
1.3.1 编译器选项
基本编译
# 编译单个文件
tsc hello.ts
# 编译多个文件
tsc file1.ts file2.ts
# 使用配置文件编译
tsc
# 监听模式
tsc --watch
# 指定输出目录
tsc --outDir dist src/*.ts
常用编译选项
# 指定目标JavaScript版本
tsc --target ES2020 hello.ts
# 指定模块系统
tsc --module commonjs hello.ts
# 生成源码映射
tsc --sourceMap hello.ts
# 严格模式
tsc --strict hello.ts
# 不生成输出文件(仅检查类型)
tsc --noEmit hello.ts
1.3.2 配置文件详解
tsconfig.json结构
{
"compilerOptions": {
// 编译选项
},
"include": [
// 包含的文件模式
],
"exclude": [
// 排除的文件模式
],
"files": [
// 明确指定的文件
],
"extends": "./base-config.json",
"compileOnSave": true,
"typeAcquisition": {
// 类型获取配置
}
}
重要编译选项说明
目标和模块
{
"compilerOptions": {
"target": "ES2020", // 目标JavaScript版本
"module": "commonjs", // 模块系统
"lib": ["ES2020", "DOM"], // 包含的库
"moduleResolution": "node" // 模块解析策略
}
}
输出控制
{
"compilerOptions": {
"outDir": "./dist", // 输出目录
"rootDir": "./src", // 根目录
"declaration": true, // 生成.d.ts文件
"declarationMap": true, // 生成声明文件映射
"sourceMap": true, // 生成源码映射
"removeComments": true // 移除注释
}
}
严格检查
{
"compilerOptions": {
"strict": true, // 启用所有严格检查
"noImplicitAny": true, // 禁止隐式any
"strictNullChecks": true, // 严格空值检查
"strictFunctionTypes": true, // 严格函数类型检查
"noImplicitReturns": true, // 禁止隐式返回
"noFallthroughCasesInSwitch": true // 禁止switch穿透
}
}
1.3.3 项目引用
多项目配置
// 根目录 tsconfig.json
{
"files": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/utils" },
{ "path": "./packages/app" }
]
}
// packages/core/tsconfig.json
{
"compilerOptions": {
"composite": true,
"declaration": true,
"outDir": "dist"
},
"include": ["src/**/*"]
}
构建项目引用
# 构建所有引用的项目
tsc --build
# 强制重新构建
tsc --build --force
# 清理构建输出
tsc --build --clean
1.4 开发工作流
1.4.1 开发模式
实时编译
# 监听模式编译
tsc --watch
# 使用ts-node直接运行
ts-node src/index.ts
# 使用nodemon自动重启
nodemon --exec ts-node src/index.ts
开发服务器配置
// package.json
{
"scripts": {
"dev": "nodemon --watch src --ext ts --exec ts-node src/index.ts",
"dev:debug": "nodemon --watch src --ext ts --exec node --inspect -r ts-node/register src/index.ts"
}
}
1.4.2 代码质量工具
集成Prettier和ESLint
# 安装依赖
npm install --save-dev prettier eslint
npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
配置脚本
{
"scripts": {
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint src/**/*.ts --fix",
"format": "prettier --write src/**/*.ts",
"format:check": "prettier --check src/**/*.ts"
}
}
Git Hooks配置
# 安装husky和lint-staged
npm install --save-dev husky lint-staged
# 初始化husky
npx husky install
# 添加pre-commit hook
npx husky add .husky/pre-commit "npx lint-staged"
// package.json
{
"lint-staged": {
"*.ts": [
"eslint --fix",
"prettier --write",
"git add"
]
}
}
1.4.3 测试环境配置
Jest配置
# 安装Jest和相关类型
npm install --save-dev jest @types/jest ts-jest
# 初始化Jest配置
npx ts-jest config:init
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src', '<rootDir>/tests'],
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
],
coverageDirectory: 'coverage',
coverageReporters: ['text', 'lcov', 'html'],
};
示例测试
// tests/greeter.test.ts
import { Greeter } from '../src/greeter';
describe('Greeter', () => {
let greeter: Greeter;
beforeEach(() => {
greeter = new Greeter('Hello');
});
test('should greet person correctly', () => {
const person = { name: 'Alice', age: 30 };
const result = greeter.greet(person);
expect(result).toBe('Hello, Alice! You are 30 years old.');
});
test('should handle empty name', () => {
const person = { name: '', age: 25 };
const result = greeter.greet(person);
expect(result).toContain('Hello, !');
});
});
1.5 常见问题和解决方案
1.5.1 编译错误
模块解析问题
// 错误:找不到模块
import { helper } from './utils/helper';
// 解决方案1:添加文件扩展名
import { helper } from './utils/helper.js';
// 解决方案2:配置模块解析
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
类型声明问题
// 错误:找不到类型声明
import express from 'express';
// 解决方案:安装类型声明
// npm install --save-dev @types/express
// 或者创建自定义声明
// types/express.d.ts
declare module 'express' {
// 类型声明
}
1.5.2 性能优化
编译性能
// tsconfig.json
{
"compilerOptions": {
"incremental": true, // 增量编译
"tsBuildInfoFile": ".tsbuildinfo", // 构建信息文件
"skipLibCheck": true, // 跳过库文件检查
"skipDefaultLibCheck": true // 跳过默认库检查
}
}
项目分割
// 使用项目引用分割大型项目
{
"references": [
{ "path": "./core" },
{ "path": "./utils" },
{ "path": "./app" }
]
}
1.5.3 调试技巧
源码映射
// tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"inlineSourceMap": false,
"inlineSources": false
}
}
调试配置
// .vscode/launch.json
{
"configurations": [
{
"name": "Debug TS",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/src/index.ts",
"runtimeArgs": ["-r", "ts-node/register"],
"sourceMaps": true,
"smartStep": true,
"skipFiles": ["<node_internals>/**"]
}
]
}
本章练习
练习1:环境搭建
- 安装Node.js和TypeScript
- 创建一个新的TypeScript项目
- 配置tsconfig.json
- 设置开发工具(VS Code或其他)
练习2:第一个程序
- 创建一个简单的计算器类
- 实现基本的数学运算方法
- 添加类型注解
- 编译并运行程序
练习3:工具配置
- 配置ESLint和Prettier
- 设置Git hooks
- 配置调试环境
- 编写简单的单元测试
练习4:项目结构
- 创建合理的目录结构
- 配置路径映射
- 设置构建脚本
- 配置开发和生产环境
通过完成这些练习,你将建立一个完整的TypeScript开发环境,为后续学习打下坚实基础。
本章总结
在本章中,我们学习了:
- TypeScript概述:了解了TypeScript的特性和优势
- 环境搭建:完成了完整的开发环境配置
- 编译器使用:掌握了TypeScript编译器的基本用法
- 开发工作流:建立了高效的开发流程
- 问题解决:学会了常见问题的解决方法
下一章我们将深入学习TypeScript的基础类型系统,这是掌握TypeScript的关键基础。