DrillLab
第 86 / 105 道86 / 105 · #355

JavaScript vs TypeScript

Javascript vs TypeScript

先自己答,再往下看Answer it yourself first

一句话:TS 是 JS 的超集—— 加了静态类型,编译后就是普通 JS, 运行时没有任何 TS 的东西

JavaScriptTypeScript
类型检查运行时才炸编译期就报
需要构建不需要需要(tsc / esbuild / SWC)
IDE 支持靠猜精确补全、跳转、重命名
重构靠搜字符串改一处,所有不兼容的地方都报出来

「运行时没有 TS」这句要强调, 因为它推出两个重要结论:

  • 类型不能用来做运行时校验。接口返回的数据是不是真的符合你写的interface, TS 管不了—— 要校验得用 zod 这类库。这是新手最大的误解。
  • as 断言只是「我保证」, 不做任何检查。滥用 asany 等于关掉了 TS。

代价(要主动说):多一步构建、 有学习成本(泛型、 条件类型、unknown vs any)、 第三方库缺类型时要自己写声明、 复杂类型报错很难读。

会追问:interfacetype 选哪个?」——interface能被重复声明合并、 更适合描述对象和 class 契约;type 能写联合、 交叉、映射、条件类型,能力更全。 实践上「对象形状用 interface, 其他用 type」,但团队统一比选哪个更重要

In one line: TS is a superset of JS — it adds static types, and after compilation it is ordinary JS with nothing of TS left at runtime.

JavaScriptTypeScript
Type checkingFails at runtimeReported at compile time
Build stepNot neededNeeded (tsc / esbuild / SWC)
IDE supportGuessworkPrecise completion, go-to-definition, rename
RefactoringSearch for stringsChange one place and every incompatible use lights up

Stress the “nothing of TS at runtime” line, because two important conclusions follow from it:

  • Types cannot validate anything at runtime. Whether the data an API returns really matches the interface you wrote is beyond TS — for that you need something like zod. This is the biggest beginner misconception.
  • An as assertion is just “trust me” and checks nothing. Overusing as and any is the same as turning TS off.

The costs — bring them up yourself: an extra build step, a learning curve (generics, conditional types, unknown vs any), writing your own declarations when a library ships none, and error messages for complex types that are hard to read.

Follow-up:interface or type?” — interface can be declared again and merged and suits object and class contracts; type can do unions, intersections, mapped and conditional types, so it is more capable. In practice: “interface for object shapes, type for everything else” — but a consistent team choice matters more than which one you pick.