类型系统初探——从 JS 到 TS 的迁移

知识库
知识库文档
/tech-stacks/typescript/examples/类型系统初探——从 JS 到 TS 的迁移.md

文档

TypeScript 例程:从 JavaScript 到 TypeScript 的类型迁移

目标

展示 TypeScript 核心类型系统:基础类型、Interface、泛型、类型守卫,并对比 JS 常见坑点。

完整代码

// ── 1. 基础类型注解 ──
let username: string = "Alice";
let age: number = 22;
let isStudent: boolean = true;
let scores: number[] = [85, 92, 78];

// ── 2. Interface 定义数据结构 ──
interface User {
  id: number;
  name: string;
  email: string;
  role?: "admin" | "user"; // 可选 + 字面量联合
  createdAt: Date;
}

const user: User = {
  id: 1,
  name: "Bob",
  email: "bob@example.com",
  role: "user",
  createdAt: new Date(),
};
// user.role = "guest";  // ❌ 编译错误!

// ── 3. 泛型函数 ──
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const n = first([1, 2, 3]);    // n: number | undefined
const s = first(["a", "b"]);   // s: string | undefined

// ── 4. 类型守卫(Type Guard) ──
function process(input: string | number): string {
  if (typeof input === "string") {
    return input.toUpperCase(); // 此处 TypeScript 知道 input 是 string
  }
  return input.toFixed(2);      // 此处 TypeScript 知道 input 是 number
}

console.log(process("hello")); // "HELLO"
console.log(process(3.1415));  // "3.14"

// ── 5. 工具类型 Utility Types ──
type ReadonlyUser = Readonly<User>;
type UserSummary = Pick<User, "id" | "name">;

const partial: Partial<User> = { name: "Temp" }; // 所有字段可选

// ── 6. JS 常见坑 → TS 捕获 ──
const obj = { x: 10 };
// console.log(obj.y.toFixed());  // ❌ TS 编译期就报错,而不是运行时

运行步骤

npm install -D typescript ts-node
npx ts-node index.ts

预期输出

HELLO
3.14

关键要点

JS 痛点 TS 解决方案
运行时才报错 编译期捕获
参数无类型约束 类型注解
无法知道对象结构 Interface/Type
any 满天飞 strict: true 禁止隐式 any

信息

路径
/tech-stacks/typescript/examples/类型系统初探——从 JS 到 TS 的迁移.md
更新时间
2026/5/31