JavaScript vs TypeScript
Javascript vs TypeScript
一句话:TS 是 JS 的超集—— 加了静态类型,编译后就是普通 JS, 运行时没有任何 TS 的东西。
| JavaScript | TypeScript | |
|---|---|---|
| 类型检查 | 运行时才炸 | 编译期就报 |
| 需要构建 | 不需要 | 需要(tsc / esbuild / SWC) |
| IDE 支持 | 靠猜 | 精确补全、跳转、重命名 |
| 重构 | 靠搜字符串 | 改一处,所有不兼容的地方都报出来 |
「运行时没有 TS」这句要强调, 因为它推出两个重要结论:
- 类型不能用来做运行时校验。接口返回的数据是不是真的符合你写的
interface, TS 管不了—— 要校验得用 zod 这类库。这是新手最大的误解。 as断言只是「我保证」, 不做任何检查。滥用as和any等于关掉了 TS。
代价(要主动说):多一步构建、 有学习成本(泛型、 条件类型、unknown vs any)、 第三方库缺类型时要自己写声明、 复杂类型报错很难读。
会追问:「interface 和type 选哪个?」——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.
| JavaScript | TypeScript | |
|---|---|---|
| Type checking | Fails at runtime | Reported at compile time |
| Build step | Not needed | Needed (tsc / esbuild / SWC) |
| IDE support | Guesswork | Precise completion, go-to-definition, rename |
| Refactoring | Search for strings | Change 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
interfaceyou wrote is beyond TS — for that you need something like zod. This is the biggest beginner misconception. - An
asassertion is just “trust me” and checks nothing. Overusingasandanyis 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.