TypeScript for the New Programmer
面向新手程序员的 TypeScript 导读
Congratulations on choosing TypeScript as one of your first languages — you’re already making good decisions!
选择 TypeScript 作为进入编程世界的第一门语言,很明智。
You’ve probably already heard that TypeScript is a “flavor”(风味 ; 滋味 ; 特色 ; 给……调味 ; 加味于) or “variant”(变种 ; 变体 ; 变形 ; 变异的 ; 不同的,相异的,不一致的 ; 多样的) of JavaScript. The relationship between TypeScript (TS) and JavaScript (JS) is rather unique among modern programming languages, so learning more about this relationship will help you understand how TypeScript adds to JavaScript.
What is JavaScript? A Brief History
JavaScript (also known as ECMAScript) (European Computer Manufacturers Association)started its life as a simple scripting language for browsers(浏览器脚本语言). At the time it was invented, it was expected to be used for short snippets of code embedded in a web page(嵌入web页面的简短代码段) — writing more than a few dozen lines of code would have been somewhat unusual (有点不寻常). Due to this, early **web browsers **executed such code pretty slowly. Over time, though(尽管如此), JS became more and more popular, and web developers started using it to create interactive experiences(互动体验).
Web browser developers responded to this increased JS usage by optimizing their execution engines(执行引擎) (dynamic compilation)(动态编译) and extending what could be done with it (adding APIs), which in turn made web developers use it even more. On modern websites, your browser is frequently(常常) running applications that span(跨越、包括) hundreds of thousands of lines(数十万行) of code. This is long and gradual growth of “the web”, starting as a simple network of static pages, and evolving into a platform for rich applications of all kinds.(Web漫长而渐进的发展,始于静态网页构成的简单网络,而后进化成为一个面向各种丰富应用程序的平台)
More than this, JS has become popular enough to be used outside the context of browsers, such as implementing JS servers using node.js(还可用于浏览器上下文/环境之外,例如使用node.js实现的JS 服务器程序). The “run anywhere” nature of JS makes it an attractive choice for cross-platform development. There are many developers these days that use only JavaScript to program their entire stack(全栈)!
To summarize(总而言之), we have a language that was designed for quick uses, and then grew to a full-fledged(成熟的) tool to write applications with millions of lines. Every language has its own quirks(怪异的性格/行为;奇特的地方) — oddities and surprises(古怪和惊喜), and JavaScript’s humble(卑微、谦逊) beginning makes it have many of these. Some examples:
- JavaScript’s equality operator (
==) coerces its arguments, leading to unexpected behavior : JS的相等运算符胁迫了它的参数,导致产生非预期的行为
if ("" == 0) {
// It is! But why??
}
if (1 < x < 3) {
// True for *any* value of x!
}
- JavaScript also allows accessing properties which aren’t present : JS还允许访问不存在的属性
const obj = { width: 10, height: 15 };
// Why is this NaN? Spelling is hard!
const area = obj.width * obj.heigth;
Most programming languages would throw an error when these sorts of(这些种类的)errors occur, some would do so during compilation(编译期) — before any code is running. When writing small programs, such quirks are annoying but manageable; when writing applications with hundreds or thousands of lines of code, these constant surprises are a serious problem.
大多数编程语言在出现此类错误时都会抛出错误,有些语言会在编译期间抛出错误——在任何代码运行之前。在编写小程序时,这样的怪癖很烦人,但可以控制;当编写具有数百或数千行代码的应用程序时,这些不断出现的意外情况是一个严重的问题。
TypeScript: A Static Type Checker
We said earlier that some languages wouldn’t allow those buggy programs(有bug的程序) to run at all. Detecting errors in code without running it is referred to as static checking. Determining what’s an error and what’s not based on the kinds of values being operated on is known as static type checking.
TypeScript checks a program for errors before execution, and does so based on the kinds of values, it’s a static type checker. For example, the last example above has an error because of the type of obj. Here’s the error TypeScript found:
A Typed Superset of JavaScript
类型化的JS超集
How does TypeScript relate to JavaScript, though?
然而,TS是怎样与JS联系起来的?
Syntax 语法方面
TypeScript is a language that is a superset of JavaScript: JS syntax is therefore legal TS. Syntax refers to the way we write text to form a program. For example, this code has a syntax error because it’s missing a ):
TypeScript doesn’t consider any JavaScript code to be an error because of its syntax. This means you can take any working JavaScript code and put it in a TypeScript file without worrying about exactly how it is written.
Types 类型方面
However, TypeScript is a typed superset, meaning that it adds rules about how different kinds of values can be used. The earlier error about obj.heigth was not a syntax error: it is an error of using some kind of value (a type) in an incorrect way.(它不是一个语法error,而是以一个错误方式使用某种类型的值的error)
As another example, this is JavaScript code that you can run in your browser, and it will log a value:
console.log(4 / []);
This syntactically-legal program logs Infinity. TypeScript, though, considers division of number by an array to be a nonsensical(无稽之谈的;荒谬的;无意义的) operation, and will issue an error:
console.log(4 / []);
The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.Try
It’s possible you really did intend to divide a number by an array, perhaps just to see what happens, but most of the time, though, this is a programming mistake. TypeScript’s type checker is designed to allow correct programs through while still catching as many common errors as possible. (Later, we’ll learn about settings you can use to configure how strictly TypeScript checks your code.)
If you move some code from a JavaScript file to a TypeScript file, you might see type errors depending on how the code is written. These may be legitimate(合法的) problems with the code, or TypeScript being overly conservative(很 ; 十分 ; 过于. 保守的,守旧的;). Throughout (自始至终) this guide we’ll demonstrate how to add various TypeScript syntax to eliminate (消除) such errors.
Runtime Behavior 运行时行为
TypeScript is also a programming language that preserves the runtime behavior of JavaScript. For example, dividing by zero in JavaScript produces Infinity instead of throwing a runtime exception. As a principle, TypeScript never changes the runtime behavior of JavaScript code.
This means that if you move code from JavaScript to TypeScript, it is guaranteed to run the same way, even if TypeScript thinks that the code has type errors.
Keeping the same runtime behavior as JavaScript is a foundational promise of TypeScript because it means you can easily transition between the two languages without worrying about subtle(微妙的,不易察觉的) differences that might make your program stop working.
Erased Types 编译擦除类型
Roughly speaking(粗略地说), once TypeScript’s compiler is done with checking your code, it erases the types to produce the resulting “compiled” code. This means that once your code is compiled, the resulting plain JS code has no type information.
一旦TypeScript的编译器检查完代码,它就会删除类型以生成结果“编译”代码。这意味着一旦编译了代码,生成的纯JS代码就没有类型信息。
This also means that TypeScript never changes the behavior of your program based on the types it inferred. The bottom line is that(基本底线,最终结果) while you might see type errors during compilation, the type system itself has no bearing on how your program works when it runs.
底线是,虽然在编译过程中可能会看到类型错误,但类型系统本身与程序运行时的工作方式无关。
Finally, TypeScript doesn’t provide any additional runtime libraries. Your programs will use the same standard library (or external libraries) as JavaScript programs, so there’s no additional TypeScript-specific framework to learn.(没有额外的TS特定的框架需要学习)
Learning JavaScript and TypeScript
We frequently see the question “Should I learn JavaScript or TypeScript?“.
The answer is that you can’t learn TypeScript without learning JavaScript!
我们经常看到这样一个问题,“我应该学习JS还是TS?”。
答案是,你不可能没学习JS就能来学TS。
TypeScript shares syntax and runtime behavior with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time.
There are many, many resources available for programmers to learn JavaScript; you should not ignore these resources if you’re writing TypeScript. For example, there are about 20 times more StackOverflow questions tagged javascript than typescript, but all of the javascript questions also apply to TypeScript.
标记为“javascript” 的StackOverflow 问题大约是“typescript”的20倍,但是所有的“javascript” 问题也适用于TypeScript.
If you find yourself searching for something like “how to sort a list in TypeScript”, remember: TypeScript is JavaScript’s runtime with a compile-time type checker. The way you sort a list in TypeScript is the same way you do so in JavaScript. If you find a resource that uses TypeScript directly, that’s great too, but don’t limit yourself to thinking you need TypeScript-specific answers for everyday questions about how to accomplish runtime tasks.
Next Steps 后续的学习步骤
This was a brief overview of the syntax and tools used in everyday TypeScript. From here, you can:
-
Learn some of the JavaScript fundamentals, we recommend either(推荐其一):
-
Continue to TypeScript for JavaScript Programmers
-
Read the full Handbook from start to finish (30m)
-
Explore the Playground examples
-
接下来,学习JavaScript基础
-
然后,继续学习
面向JavaScript程序员的TypeScript学习导读 -
然后,从头到尾读完整个手册 Handbook (30分钟)
-
探索体验 Playgound 演练场 上的例子