原文:https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html
下面是本人对官方文档TypeScript for the New Programmer的翻译。
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.
您可能已经听说过TypeScript是JavaScript的 “味道” 或 “变体”。在现代编程语言中,TypeScript (TS) 和JavaScript (JS) 之间的关系相当独特,因此了解更多有关这种关系的信息将帮助您了解TypeScript如何添加到JavaScript中。
What is JavaScript? A Brief History(什么是JavaScript?简史)
JavaScript (also known as ECMAScript) 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 — 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.
JavaScript (也被称为ECMAScript) 作为一种简单的浏览器脚本语言开始了它的生命。在它被发明的时候,它被期望被用于嵌入网页的代码的短片段 — 编写几十行代码会有些不寻常。因此,早期的web浏览器执行此类代码的速度非常慢。然而,随着时间的推移,JS变得越来越流行,web开发人员开始使用它来创建交互体验。
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.
随着JS应用的越来越多,Web浏览器开发人员优化其执行引擎 (动态编译) 和扩展使用它可以做的事情 (添加API)。这反过来使web开发人员更多地使用它。在现代网站上,您的浏览器经常运行跨越数十万行代码的应用程序。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. 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!
不仅如此,JS已经变得足够流行,可以在浏览器的环境之外使用,例如使用node.JS实现JS服务器。JS的 “在任何地方运行” 特性使其成为跨平台开发的一个有吸引力的选择。如今有许多开发人员只使用JavaScript来编程他们的整个堆栈!
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卑微的开端使它有许多这样的怪癖。一些例子:
JavaScript’s equality operator (
==
) coerces its arguments, leading to unexpected behavior:
- JavaScript的相等运算符 ((
==
) 强制其参数,导致意外行为:
```javascript 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:
- JavaScript还允许访问不存在的属性:
```javascript
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 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:
TypeScript在执行之前检查程序是否有错误,并根据值的种类进行检查,它是静态类型检查器。例如,上述最后一个示例由于obj的类型而出现错误。这是发现的错误TypeScript:
const obj = { width: 10, height: 15 };
const area = obj.width * obj.heigth;
Property 'heigth' does not exist on type '{ width: number; height: number; }'. Did you mean 'height'?
A Typed Superset of JavaScript(JavaScript的类型化超集)
How does TypeScript relate to JavaScript, though?
不过,TypeScript与JavaScript有什么关系?
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是JavaScript的超集语言: 因此,JS语法是合法的TS。语法是指我们编写文本以形成程序的方式。例如,此代码有语法错误,因为它缺少)
:
let a = (4
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.
由于其语法,TypeScript不认为任何JavaScript代码是错误的。这意味着您可以获取任何有效的JavaScript代码并将其放入TypeScript文件中,而不必担心它是如何编写的。
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.
但是,TypeScript是一个类型化超集,这意味着它添加了有关如何使用不同类型的值的规则。关于obj.heigth
的较早错误不是语法错误: 这是以不正确的方式使用某种值 (类型) 的错误。
As another example, this is JavaScript code that you can run in your browser, and it will log a value:
作为另一个示例,这是您可以在浏览器中运行的JavaScript代码,它将记录一个值:
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:
这个语法合法的程序在控制台中输出Infinity
。但是,TypeScript认为数组除数是无意义的操作,并且会发出错误:
The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
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.)
有可能你真的打算用数组除数,也许只是为了看看会发生什么,但是大多数时候,这是一个编程错误。TypeScript的类型检查器旨在允许正确的程序通过,同时仍然捕获尽可能多的常见错误。(稍后,我们将了解可用于配置TypeScript如何严格检查代码的设置。)
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.
如果将某些代码从JavaScript文件移动到TypeScript文件,则可能会看到类型错误,具体取决于代码的编写方式。这些可能是代码的合法问题,或者TypeScript过于保守。在本指南中,我们将演示如何添加各种TypeScript语法来消除此类错误。
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 neverchanges the runtime behavior of JavaScript code.
TypeScript也是一种保留JavaScript运行时行为的编程语言。例如,在JavaScript中除以零会产生Infinity
,而不是引发运行时异常。作为一个原则,TypeScript从不改变JavaScript代码的运行时行为。
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.
这意味着,如果将代码从JavaScript移动到TypeScript,即使TypeScript认为代码存在类型错误,也可以保证以相同的方式运行。
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.
保持与JavaScript相同的运行时行为是TypeScript的基本承诺,因为这意味着您可以轻松地在两种语言之间进行转换,而不必担心可能使程序停止工作的细微差异。
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.
这也意味着TypeScript永远不会根据其推断的类型来改变程序的行为。最重要的是,虽然在编译过程中可能会看到类型错误,但类型系统本身与程序运行时的工作方式无关。
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.
最后,TypeScript不提供任何额外的运行时库。您的程序将使用与JavaScript程序相同的标准库 (或外部库),因此没有其他特定于TypeScript的框架可供学习。
Learning JavaScript and TypeScript
We frequently see the question “Should I learn JavaScript or TypeScript?“.
我们经常看到这样一个问题: “我应该学习JavaScript还是TypeScript?”。
The answer is that you can’t learn TypeScript without learning JavaScript! TypeScript shares syntax and runtime behavior with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time.
答案是,如果不学习JavaScript,就无法学习TypeScript! TypeScript与JavaScript共享语法和运行时行为,因此您学到的有关JavaScript的任何内容都可以帮助您同时学习TypeScript。
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
thantypescript
, but all of thejavascript
questions also apply to TypeScript.
有很多很多资源可供程序员学习JavaScript; 如果你正在编写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.
如果您发现自己在搜索 “如何在TypeScript中对列表进行排序” 之类的内容,请记住: TypeScript是带有编译时类型检查器的JavaScript运行时。在TypeScript中对列表进行排序的方式与在JavaScript中进行排序的方式相同。如果你发现一个直接使用TypeScript的资源,那也很好,但是不要局限于认为你需要针对如何完成运行时任务的日常问题的特定TypeScript答案。