跳到主要内容

环境与工具链

本模块约定 TypeScript 5.0+。假设你已会 JavaScript;先把编译器与运行方式跑通。

安装​

全局(适合随手试):

npm install -g typescript
tsc --version
# 期望:Version 5.x.x

更推荐在项目里本地安装,避免全局版本漂移:

mkdir hello-ts && cd hello-ts
npm init -y
npm install -D typescript
npx tsc --version

第一个文件:编译再运行​

hello.ts:

const message: string = "hello, typescript";
console.log(message);
npx tsc hello.ts
node hello.js

tsc 把 .ts 编译成 .js;真正执行的是 JS 运行时(Node / 浏览器)。

tsconfig.json 初识​

npx tsc --init

会生成 tsconfig.json。先关心这几项:

选项直觉
target输出 JS 的语法版本(如 ES2020)
module模块系统(如 NodeNext / ESNext)
strict打开一整套严格检查(强烈建议)
rootDir / outDir源码目录与输出目录

有 tsconfig.json 后,在项目根执行:

npx tsc

会按配置编译整个工程,而不是只编单个文件。

直接跑 TS:tsx​

开发时不想每次手动 tsc,可用 tsx:

npm install -D tsx
npx tsx hello.ts
  • 学习 / 构建产物:用 tsc 看类型错误与输出
  • 本地脚本调试:用 tsx 更快

要点​

  1. 确认 TypeScript ≥ 5.0
  2. 会用 tsc 编译、node 运行
  3. 知道 tsconfig.json 管整个项目
  4. 开发调试可用 tsx,与「类型检查」是两条线