Skip to content

TypeScript 对比 JavaScript

如何 TypeScript differs 从 JavaScript: 静态类型, 编译-时间检查, and tooling.

你将学到

  • 键 differences 之间 TypeScript and JavaScript
  • 什么编译-时间类型检查平均值 in 练习
  • 如何 TypeScript improves developer tooling and refactoring
  • 当到 选择 TypeScript over plain JavaScript

概念讲解

The Core Difference

The fundamental difference is when types are checked. JavaScript checks types at runtime — if you call undefined.foo(), the error only appears when that line executes. TypeScript checks types at compile time — the compiler knows undefined has no method foo and warns you before you ever run the code. This shift from "查找 bugs in production" to "查找 bugs in 你的 editor" is the single biggest benefit.

What TypeScript Adds

TypeScript adds: type annotations (let x: 数字), interfaces and type aliases for describing object shapes, generics for reusable typed code, union and intersection types for flexible modeling, and utility types for transforming existing types. None of these exist in plain JavaScript. The TypeScript compiler also provides far richer autocompletion, inline documentation, and refactoring support.

What TypeScript Does Not Change

TypeScript does not change JavaScript's runtime behavior. There is no type information at runtime — no reflection, no runtime type guards based on TS types. TypeScript also does not make your code faster; the compiled output is the same JavaScript you would have written by hand. It makes you faster and more confident, not the machine.

示例代码

              // JavaScript version — no type safety, bugs surface at runtime.
function jsTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// TypeScript version — compiler validates shapes and catches errors.
interface CartItem {
  name: string;
  price: number;
  quantity: number;
}

function tsTotal(items: CartItem[]): number {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

const cart: CartItem[] = [
  { name: "Book", price: 12.99, quantity: 2 },
  { name: "Pen", price: 1.5, quantity: 5 },
];
console.log(tsTotal(cart)); // 33.48
            

JS version 接受任何事 and 失败 silently 如果 shape 是错误. TS version guarantees 每个项 有 name, price, and 数量 — 编译器 enforces 它.

动手试一试

  • JSON 到 TypeScript

    See 如何 JSON shapes become 输入 TypeScript 接口.

  • Code Diff

    Compare 输入 and untyped versions 的相同 logic.

常见错误

错误写法

Expecting TypeScript 到验证类型 at 运行时

正确做法

TypeScript 类型是 编译-时间仅. For 运行时 validation (e.g. parsing API 响应), use validation 库如 zod or io-ts.

错误写法

添加所以许多类型那个 code becomes 困难到 读取

正确做法

Use 类型 inference 哪里可能. Let TypeScript infer 类型 for 简单变量 and 仅 annotate 函数 signatures and 复杂类型.

练习 TypeScript 对比 JavaScript

3 个练习

练习 TypeScript 对比 JavaScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误