Banner

TypeScript 6.x

2026-11-06

下面是一份按 2026 年主流实践整理的 TypeScript 上手教程。当前稳定主线是 TypeScript 6.x,7.0 正在推进原生编译器迁移,所以新项目建议直接按 6.0+ 的现代默认值配置。

1. 先装 Node.js

推荐安装 Node.js 18+,如果做新项目,直接选 20/22/24 LTS 更省心。

终端验证:

node -v
npm -v

2. 初始化项目

建议把 TypeScript 安装在项目里,不要只靠全局安装,这样团队和 CI 环境更稳定。

mkdir ts-starter
cd ts-starter
npm init -y
npm install --save-dev typescript @types/node
npx tsc --init

3. 写一个最小组件

创建 src/index.ts:

function greet(name: string): string {
  return `Hello, ${name}!`;
}

console.log(greet("TypeScript"));

4. 配置 tsconfig.json

TypeScript 6.0 之后默认值变化较大:strict 默认开启,module 默认 esnext,target 默认 es2025,types 默认空数组。

Node.js 项目推荐这样配:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "sourceMap": true,
    "types": ["node"]
  },
  "include": ["src"]
}

几个容易踩坑的点:

  • module / moduleResolution:Node.js 项目优先用 NodeNext,不要随便写 commonjs + bundler 混用。
  • rootDir:6.0 后默认值变成配置文件所在目录,通常要显式设为 ./src。
  • types: ["node"]:6.0 后不会自动加载所有 @types,缺少它可能导致 process、fs 等找不到类型。
  • noUncheckedIndexedAccess:开启后数组索引会得到 T | undefined,更安全。

5. 编译和运行

npx tsc
node dist/index.js

开发时可以监听变化:

npx tsc --watch

如果想直接运行 TS 文件,可以安装 tsx 或 ts-node:

npm install --save-dev tsx

然后在 package.json 里加:

{
  "scripts": {
    "dev": "tsx watch src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

6. 快速掌握核心语法

// 基础类型
let name: string = "TS";
let age: number = 18;
let active: boolean = true;

// 函数
function add(a: number, b: number): number {
  return a + b;
}

// 接口
interface User {
  id: number;
  name: string;
  email?: string;
}

// 联合类型
type Status = "idle" | "loading" | "success" | "error";

// 泛型
function first<T>(items: T[]): T | undefined {
  return items[0];
}

// satisfies:保持具体类型,同时满足约束
const config = {
  port: 3000,
  host: "localhost",
} satisfies Record<string, number | string>;


12