📦 前置要求
在安装 TypeScript 之前,需要先安装 Node.js 和 npm:
# 检查 Node.js 版本
node -v
# 建议版本: v18.x 或更高
# 检查 npm 版本
npm -v
# 建议版本: v9.x 或更高
💡
下载 Node.js
访问 nodejs.org 下载并安装 LTS 版本,npm 会随 Node.js 一起安装。
🔧 安装方式
方式一:全局安装(推荐)
# 使用 npm 全局安装
npm install -g typescript
# 验证安装
tsc -v
# 输出: Version 5.x.x
方式二:项目本地安装
# 在项目中安装
npm install typescript --save-dev
# 使用 npx 运行
npx tsc -v
# 或在 package.json scripts 中使用
# "scripts": { "build": "tsc" }
方式三:安装特定版本
# 安装特定版本
npm install -g typescript@4.9.5
# 安装最新版本
npm install -g typescript@latest
# 安装下一版本(beta/rc)
npm install -g typescript@next
💻 tsc 编译器基本使用
编译单个文件
# 创建 TypeScript 文件
echo "const greeting: string = 'Hello TypeScript';" > hello.ts
# 编译为 JavaScript
tsc hello.ts
# 查看生成的 JavaScript 文件
cat hello.js
# 输出: var greeting = 'Hello TypeScript';
常用编译选项
# 指定输出目录
tsc hello.ts --outDir ./dist
# 指定目标 ES 版本
tsc hello.ts --target ES2020
# 开启严格模式
tsc hello.ts --strict
# 监听文件变化
tsc hello.ts --watch
# 显示帮助
tsc --help
🔄 更新和卸载
# 更新到最新版本
npm update -g typescript
# 卸载全局安装
npm uninstall -g typescript
# 查看已安装版本
npm list -g typescript
⚠️
版本兼容性
更新 TypeScript 版本前,建议查看 官方文档 了解新版本变化,避免破坏性更新影响项目。