TypeScript Overview
什么 TypeScript 是, 为什么它 添加类型到 JavaScript, and 如何它 catches 错误之前运行时.
你将学到
- 什么 TypeScript 是 and 如何它 relates 到 JavaScript
- 为什么静态类型 catch bugs 之前你的 code 运行
- 如何 TypeScript 编译器 (tsc) transforms .ts files 到 .js
- 哪里 TypeScript 是 used: 前面-端, 后面-端, and tooling
概念讲解
什么是 TypeScript?
TypeScript is a strongly typed programming language that builds on JavaScript by adding static type annotations. It was created by Microsoft in 2012 and is now one of the most popular languages in the world. Every valid JavaScript program is also a valid TypeScript program — TypeScript is a superset of JavaScript. You can adopt it incrementally: rename your .ts files and add types only where they help.
Why Static Types Matter
JavaScript is dynamically typed, so variable types are determined at runtime. This flexibility is convenient but dangerous: a typo like 用户.namme instead of 用户.name will not surface until the code runs, possibly in production. TypeScript checks types at compile time — before the code ever executes. The compiler reports mismatches immediately, turning an entire class of runtime bugs into instant editor warnings.
How TypeScript Works
You write code in .ts (or .tsx for React) files. The TypeScript compiler (tsc) reads those files, type-checks them, and erases all type information to produce plain JavaScript. The types exist only during development; they cost nothing at runtime. This process is called "transpilation" — translating TypeScript into JavaScript while validating correctness.
示例代码
// TypeScript adds type annotations on top of JavaScript.
let username: string = "alice";
let age: number = 30;
let isActive: boolean = true;
// The compiler catches type errors before you run the code.
// username = 42; // ❌ Error: Type 'number' is not assignable to type 'string'.
// Types are erased at compile time — the output is plain JS.
function greet(name: string): string {
return "Hello, " + name;
}
console.log(greet(username));
保存这个 as .ts and 运行 tsc 到编译. 类型 annotations (字符串, 数字, 布尔值) 是检查通过编译器但 移除从 最终 .js 输出.
动手试一试
- JSON 到 TypeScript
Convert JSON 数据到 TypeScript 接口 — see 类型 in 操作.
- Code Diff
Compare TypeScript 输出使用它的 JavaScript compilation.
常见错误
错误写法
Thinking TypeScript 是 completely 不同 language 从 JavaScript
正确做法
TypeScript 是 superset 的 JavaScript. 所有有效 JS 是有效 TS. 你能 开始通过简单地 renaming .js 到 .ts.
错误写法
Believing 类型运行 at 运行时 and 慢下 你的 app
正确做法
类型是 erased 期间 compilation. 输出是 plain JavaScript 使用零 运行时类型-检查 overhead.
相关资源
相关速查表
- TypeScript Cheatsheet
快速引用 for TypeScript 语法 and 常见模式.
练习 TypeScript Overview
4 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。