什么是 TypeScript,为什么我要用它来代替 JavaScript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12694530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:02:56  来源:igfitidea点击:

What is TypeScript and why would I use it in place of JavaScript?

javascripttypescript

提问by Mohammed Thabet

Can you please describe what the TypeScript language is?

你能描述一下什么是 TypeScript 语言吗?

What can it do that JavaScript or available libraries cannot do, that would give me reason to consider it?

它可以做什么 JavaScript 或可用库不能做的事情,这让我有理由考虑它?

采纳答案by Paul Dixon

I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answerbelow for more depth

我最初在 TypeScript 仍然很火的时候写了这个答案。五年后,这是一个不错的概述,但请查看下面Lodewijk 的回答以获得更深入的信息

1000ft view...

1000英尺视野...

TypeScriptis a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

TypeScript是 JavaScript 的超集,主要提供可选的静态类型、类和接口。最大的好处之一是使 IDE 能够提供更丰富的环境,以便在您键入代码时发现常见错误。

To get an idea of what I mean, watch Microsoft's introductory videoon the language.

要了解我的意思,请观看微软关于该语言的介绍视频

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

对于大型 JavaScript 项目,采用 TypeScript 可能会产生更强大的软件,同时仍可部署在常规 JavaScript 应用程序运行的地方。

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

它是开源的,但如果您使用受支持的 IDE,您只能在键入时获得聪明的 Intellisense。最初,这只是 Microsoft 的 Visual Studio(也在Miguel de Icaza 的博客文章中提到)。如今其他 IDE 也提供 TypeScript 支持

Are there other technologies like it?

还有其他类似的技术吗?

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for toolsthrough its optional static typing (see this recent blog postfor a little more critique). There's also Dartbut that's a full on replacement for JavaScript (though it can produce JavaScript code)

CoffeeScript,但它确实有不同的用途。恕我直言,CoffeeScript 为人类提供了可读性,但 TypeScript 还通过其可选的静态类型为工具提供了深度可读性(请参阅最近的博客文章以获得更多批评)。还有Dart,但它完全替代了 JavaScript(尽管它可以生成 JavaScript 代码

Example

例子

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

例如,这里有一些 TypeScript(您可以在TypeScript Playground 中使用它

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  

And here's the JavaScript it would produce

这是它会产生的 JavaScript

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

请注意 TypeScript 如何定义成员变量和类方法参数的类型。这在转换为 JavaScript 时被删除,但被 IDE 和编译器用来发现错误,比如将数字类型传递给构造函数。

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet()method returns a string.

它还能够推断未显式声明的类型,例如,它会确定greet()方法返回一个字符串。

Debugging TypeScript

调试打字稿

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

许多浏览器和 IDE 通过源映射提供直接调试支持。有关更多详细信息,请参阅此堆栈溢出问题:使用 Visual Studio 调试 TypeScript 代码

Want to know more?

想知道更多?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answerto this question for some more current detail.

我最初在 TypeScript 仍然很火的时候写了这个答案。查看Lodewijk对此问题的回答,了解更多最新细节。

回答by Lodewijk Bogaards

TypeScript's relation to JavaScript

TypeScript 与 JavaScript 的关系

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript - typescriptlang.org.

TypeScript 是 JavaScript 的类型化超集,可编译为纯 JavaScript - typescriptlang.org

JavaScript is a programming language that is developed by EMCA's Technical Committee 39, which is a group of people composed of many different stakeholders. TC39 is a committee hosted by ECMA: an internal standards organization. JavaScript has many different implementations by many different vendors (e.g. Google, Microsoft, Oracle, etc.). The goal of JavaScript is to be the lingua franca of the web.

JavaScript 是由EMCA 的技术委员会 39开发的一种编程语言,该委员会由许多不同的利益相关者组成。TC39 是一个由ECMA主办的委员会:一个内部标准组织。许多不同的供应商(例如 Google、Microsoft、Oracle 等)对 JavaScript 有许多不同的实现。JavaScript 的目标是成为网络的通用语言。

TypeScript is a superset of the JavaScript language that has a single open-source compiler and is developed mainly by a single vendor: Microsoft. The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient.

TypeScript 是 JavaScript 语言的超集,它有一个开源编译器,主要由一个供应商开发:微软。TypeScript 的目标是帮助通过类型系统及早发现错误并使 JavaScript 开发更高效。

Essentially TypeScript achieves its goals in three ways:

本质上,TypeScript 通过三种方式实现其目标:

  1. Support for modern JavaScript features- The JavaScript language (not the runtime) is standardized through the ECMAScriptstandards. Not all browsers and JavaScript runtimes support all features of all ECMAScript standards (see this overview). TypeScript allows for the use of many of the latest ECMAScript features and translates them to older ECMAScript targets of your choosing (see the list of compile targetsunder the --targetcompiler option). This means that you can safely use new features, like modules, lambda functions, classes, the spread operator and destructuring, while remaining backwards compatible with older browsers and JavaScript runtimes.

  2. Advanced type system- The type support is not part of the ECMAScript standard and will likely never be due to the interpreted nature instead of compiled nature of JavaScript. The type system of TypeScript is incredibly rich and includes: interfaces, enums, hybrid types, generics, union/intersection types, access modifiers and much more. The official websiteof TypeScript gives an overview of these features. Typescript's type system is on-par with most other typed languages and in some cases arguably more powerful.

  3. Developer tooling support- TypeScript's compiler can run as a background process to support both incremental compilation and IDE integration such that you can more easily navigate, identify problems, inspect possibilities and refactor your codebase.

  1. 支持现代 JavaScript 功能- JavaScript 语言(不是运行时)通过ECMAScript标准进行标准化。并非所有浏览器和 JavaScript 运行时都支持所有 ECMAScript 标准的所有功能(请参阅此概述)。TypeScript 允许使用许多最新的 ECMAScript 功能,并将它们转换为您选择的旧 ECMAScript 目标(请参阅编译--target器选项下的编译目标列表)。这意味着您可以安全地使用新功能,如模块、lambda 函数、类、展开运算符和解构,同时保持与旧浏览器和 JavaScript 运行时的向后兼容。

  2. 高级类型系统- 类型支持不是 ECMAScript 标准的一部分,并且可能永远不会是由于 JavaScript 的解释性质而不是编译性质。TypeScript 的类型系统非常丰富,包括:接口、枚举、混合类型、泛型、联合/交集类型、访问修饰符等等。TypeScript的官方网站提供了这些功能的概述。Typescript 的类型系统与大多数其他类型语言相当,并且在某些情况下可以说更强大。

  3. 开发人员工具支持- TypeScript 的编译器可以作为后台进程运行,以支持增量编译和 IDE 集成,以便您可以更轻松地导航、识别问题、检查可能性和重构代码库。

TypeScript's relation to other JavaScript targeting languages

TypeScript 与其他 JavaScript 目标语言的关系

TypeScript has a unique philosophy compared to other languages that compile to JavaScript. JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can almost rename your .jsfiles to .tsfiles and start using TypeScript (see "JavaScript interoperability" below). TypeScript files are compiled to readable JavaScript, so that migration back is possible and understanding the compiled TypeScript is not hard at all. TypeScript builds on the successes of JavaScript while improving on its weaknesses.

与编译为 JavaScript 的其他语言相比,TypeScript 具有独特的理念。JavaScript 代码是有效的 TypeScript 代码;TypeScript 是 JavaScript 的超集。您几乎可以将.js文件重命名为.ts文件并开始使用 TypeScript(请参阅下面的“JavaScript 互操作性”)。TypeScript 文件被编译为可读的 JavaScript,因此迁移回是可能的,并且理解编译的 TypeScript 一点也不难。TypeScript 建立在 JavaScript 的成功之上,同时改进了它的弱点。

On the one hand, you have future proof tools that take modern ECMAScript standards and compile it down to older JavaScript versions with Babel being the most popular one. On the other hand, you have languages that may totally differ from JavaScript which target JavaScript, like CoffeeScript, Clojure, Dart, Elm, Haxe, Scala.js, and a whole host more (see this list). These languages, though they might be better than where JavaScript's future might ever lead, run a greater risk of not finding enough adoption for their futures to be guaranteed. You might also have more trouble finding experienced developers for some of these languages, though the ones you will find can often be more enthusiastic. Interop with JavaScript can also be a bit more involved, since they are farther removed from what JavaScript actually is.

一方面,您拥有面向未来的工具,这些工具采用现代 ECMAScript 标准并将其编译为较旧的 JavaScript 版本,其中 Babel 是最受欢迎的版本。另一方面,您的语言可能与针对 JavaScript 的 JavaScript 完全不同,例如 CoffeeScript、Clojure、Dart、Elm、Haxe、Scala.js 和更多主机(请参阅此列表)。这些语言,虽然它们可能比 JavaScript 的未来可能领先,但冒着更大的风险,无法找到足够的采用来保证它们的未来。您可能也很难为其中一些语言找到有经验的开发人员,尽管您会找到的开发人员通常更热情。与 JavaScript 的互操作也可能涉及更多,因为它们与 JavaScript 的实际情况相距甚远。

TypeScript sits in between these two extremes, thus balancing the risk. TypeScript is not a risky choice by any standard. It takes very little effort to get used to if you are familiar with JavaScript, since it is not a completely different language, has excellent JavaScript interoperability support and it has seen a lot of adoption recently.

TypeScript 介于这两个极端之间,从而平衡了风险。从任何标准来看,TypeScript 都不是一个冒险的选择。如果您熟悉 JavaScript,则只需很少的努力就可以适应它,因为它不是一种完全不同的语言,具有出色的 JavaScript 互操作性支持,并且最近已被大量采用。

Optionally static typing and type inference

可选的静态类型和类型推断

JavaScript is dynamically typed. This means JavaScript does not know what type a variable is until it is actually instantiated at run-time. This also means that it may be too late. TypeScript adds type support to JavaScript. Bugs that are caused by false assumptions of some variable being of a certain type can be completely eradicated if you play your cards right (how strict you type your code or if you type your code at all is up to you).

JavaScript 是动态类型的。这意味着 JavaScript 不知道变量是什么类型,直到它在运行时实际实例化。这也意味着可能为时已晚。TypeScript 为 JavaScript 添加了类型支持。如果您正确地打牌(您键入代码的严格程度或是否键入代码取决于您),则可以完全消除由某些变量属于某种类型的错误假设引起的错误。

TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. For example: var x = "hello"in TypeScript is the same as var x : string = "hello". The type is simply inferred from its use. Even it you don't explicitly type the types, they are still there to save you from doing something which otherwise would result in a run-time error.

通过使用类型推断,TypeScript 使打字变得更容易,也更不明确。例如:var x = "hello"在 TypeScript 中与var x : string = "hello". 类型只是从它的使用中推断出来的。即使您没有明确键入类型,它们仍然可以避免您做一些会导致运行时错误的事情。

TypeScript is optionally typed by default. For example function divideByTwo(x) { return x / 2 }is a valid function in TypeScript which can be called with anykind of parameter, even though calling it with a string will obviously result in a runtimeerror. Just like you are used to in JavaScript. This works, because when no type was explicitly assigned and the type could not be inferred, like in the divideByTwo example, TypeScript will implicitly assign the type any. This means the divideByTwo function's type signature automatically becomes function divideByTwo(x : any) : any. There is a compiler flag to disallow this behavior: --noImplicitAny. Enabling this flag gives you a greater degree of safety, but also means you will have to do more typing.

默认情况下,TypeScript 是可选类型的。例如function divideByTwo(x) { return x / 2 },TypeScript 中的有效函数可以使用任何类型的参数调用,即使使用字符串调用它显然会导致运行时错误。就像您在 JavaScript 中习惯的那样。这是有效的,因为当没有明确分配类型并且无法推断类型时,就像在divideByTwo 示例中一样,TypeScript 将隐式分配类型any。这意味着divideByTwo 函数的类型签名会自动变为function divideByTwo(x : any) : any。有一个编译器标志禁止这种行为:--noImplicitAny。启用此标志可为您提供更大程度的安全性,但也意味着您将不得不进行更多的输入。

Types have a cost associated with them. First of all, there is a learning curve, and second of all, of course, it will cost you a bit more time to set up a codebase using proper strict typing too. In my experience, these costs are totally worth it on any serious codebase you are sharing with others. A Large Scale Study of Programming Languages and Code Quality in Githubsuggests that "statically typed languages, in general, are less defect prone than the dynamic types, and that strong typing is better than weak typing in the same regard".

类型具有与之相关的成本。首先,有一个学习曲线,其次,当然,使用正确的严格类型设置代码库也会花费你更多的时间。根据我的经验,在您与他人共享的任何严肃的代码库中,这些成本是完全值得的。Github 中对编程语言和代码质量的大规模研究表明“静态类型语言通常比动态类型更不容易出现缺陷,并且在相同方面强类型优于弱类型”。

It is interesting to note that this very same paper finds that TypeScript is less error-prone than JavaScript:

有趣的是,同一篇论文发现 TypeScript 比 JavaScript 更不容易出错:

For those with positive coefficients we can expect that the language is associated with, ceteris paribus, a greater number of defect fixes. These languages include C, C++, JavaScript, Objective-C, Php, and Python. The languages Clojure, Haskell, Ruby, Scala, and TypeScript, all have negative coefficients implying that these languages are less likely than the average to result in defect fixing commits.

对于那些具有正系数的人,我们可以预期语言与其他条件相同的缺陷修复程序相关联。这些语言包括 C、C++、JavaScript、Objective-C、Php 和 Python。Clojure、Haskell、Ruby、Scala 和TypeScript语言都具有负系数,这意味着这些语言不太可能导致缺陷修复提交。

Enhanced IDE support

增强的 IDE 支持

The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information. This gives a couple of major advantages. For example, with TypeScript, you can safely do refactorings like renames across your entire codebase. Through code completion, you can get inline help on whatever functions a library might offer. No more need to remember them or look them up in online references. Compilation errors are reported directly in the IDE with a red squiggly line while you are busy coding. All in all, this allows for a significant gain in productivity compared to working with JavaScript. One can spend more time coding and less time debugging.

TypeScript 的开发体验是对 JavaScript 的巨大改进。TypeScript 编译器会实时通知 IDE 其丰富的类型信息。这提供了几个主要优点。例如,使用 TypeScript,您可以安全地在整个代码库中进行重构,例如重命名。通过代码完成,您可以获得有关库可能提供的任何功能的内联帮助。不再需要记住它们或在在线参考资料中查找它们。当您忙于编码时,编译错误会直接在 IDE 中用红色波浪线报告。总而言之,与使用 JavaScript 相比,这可以显着提高生产力。人们可以花更多的时间编码和更少的时间调试。

There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio Code, WebStorm, Atom and Sublime.

有很多 IDE 对 TypeScript 有很好的支持,例如 Visual Studio Code、WebStorm、Atom 和 Sublime。

Strict null checks

严格的空检查

Runtime errors of the form cannot read property 'x' of undefinedor undefined is not a functionare very commonly caused by bugs in JavaScript code. Out of the box TypeScript already reduces the probability of these kinds of errors occurring, since one cannot use a variable that is not known to the TypeScript compiler (with the exception of properties of anytyped variables). It is still possible though to mistakenly utilize a variable that is set to undefined. However, with the 2.0 version of TypeScript you can eliminate these kinds of errors all together through the usage of non-nullable types. This works as follows:

表单的运行时错误cannot read property 'x' of undefinedundefined is not a function由 JavaScript 代码中的错误引起的非常常见。开箱即用的 TypeScript 已经降低了发生此类错误的可能性,因为不能使用 TypeScript 编译器不知道的变量(any类型化变量的属性除外)。但仍有可能错误地使用设置为 的变量undefined。但是,使用 2.0 版本的 TypeScript,您可以通过使用不可为 null 的类型来消除这些类型的错误。其工作原理如下:

With strict null checks enabled (--strictNullCheckscompiler flag) the TypeScript compiler will not allow undefinedto be assigned to a variable unless you explicitly declare it to be of nullable type. For example, let x : number = undefinedwill result in a compile error. This fits perfectly with type theory since undefinedis not a number. One can define xto be a sum type of numberand undefinedto correct this: let x : number | undefined = undefined.

启用严格的空检查(--strictNullChecks编译器标志)后,TypeScript 编译器将不允许undefined分配给变量,除非您明确声明它为可空类型。例如,let x : number = undefined会导致编译错误。这完全符合类型理论,因为undefined它不是数字。可以定义x为一个和类型numberundefined更正此:let x : number | undefined = undefined

Once a type is known to be nullable, meaning it is of a type that can also be of the value nullor undefined, the TypeScript compiler can determine through control flow based type analysis whether or not your code can safely use a variable or not. In other words when you check a variable is undefinedthrough for example an ifstatement the TypeScript compiler will infer that the type in that branch of your code's control flow is not anymore nullable and therefore can safely be used. Here is a simple example:

一旦已知一个类型可以为空,这意味着它的类型也可以是值nullor undefined,TypeScript 编译器可以通过基于控制流的类型分析来确定您的代码是否可以安全地使用变量。换句话说,当您undefined通过例如一条if语句检查变量时,TypeScript 编译器将推断代码控制流的该分支中的类型不再可以为空,因此可以安全地使用。这是一个简单的例子:

let x: number | undefined;
if (x !== undefined) x += 1; // this line will compile, because x is checked.
x += 1; // this line will fail compilation, because x might be undefined.

During the build, 2016 conference co-designer of TypeScript Anders Hejlsberg gave a detailed explanation and demonstration of this feature: video(from 44:30 to 56:30).

在构建过程中,TypeScript 2016 会议联合设计师 Anders Hejlsberg 对该功能进行了详细的解释和演示:视频(从 44:30 到 56:30)。

Compilation

汇编

To use TypeScript you need a build process to compile to JavaScript code. The build process generally takes only a couple of seconds depending of course on the size of your project. The TypeScript compiler supports incremental compilation (--watchcompiler flag) so that all subsequent changes can be compiled at greater speed.

要使用 TypeScript,您需要一个构建过程来编译为 JavaScript 代码。构建过程通常只需要几秒钟,具体取决于项目的大小。TypeScript 编译器支持增量编译(--watch编译器标志),以便可以更快地编译所有后续更改。

The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. Source map information can be used by debugging utilities like the Chrome DevTools and other IDE's to relate the lines in the JavaScript to the ones that generated them in the TypeScript. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code. Source map information works pretty well, it was around long before TypeScript, but debugging TypeScript is generally not as great as when using JavaScript directly. Take the thiskeyword for example. Due to the changed semantics of the thiskeyword around closures since ES2015, thismay actually exists during runtime as a variable called _this(see this answer). This may confuse you during debugging but generally is not a problem if you know about it or inspect the JavaScript code. It should be noted that Babel suffers the exact same kind of issue.

TypeScript 编译器可以在生成的 .js 文件中内联源映射信息或创建单独的 .map 文件。调试实用程序(如 Chrome DevTools 和其他 IDE)可以使用源映射信息将 JavaScript 中的行与在 TypeScript 中生成它们的行相关联。这使您可以在运行时直接在 TypeScript 代码上设置断点和检查变量。源映射信息工作得很好,早在 TypeScript 之前就已经存在了,但是调试 TypeScript 通常不如直接使用 JavaScript 时那么好。以 this关键字为例。由于this自 ES2015 以来围绕闭包的关键字的语义发生了变化,this实际上可能在运行时作为调用的变量存在_this(请参阅此答案)。这可能会使您在调试期间感到困惑,但如果您了解它或检查 JavaScript 代码,这通常不是问题。应该注意的是,Babel 遇到了完全相同的问题。

There are a few other tricks the TypeScript compiler can do, like generating intercepting code based on decorators, generating module loading code for different module systems and parsing JSX. However, you will likely require a build tool besides the Typescript compiler. For example, if you want to compress your code you will have to add other tools to your build process to do so.

TypeScript 编译器还有一些其他的技巧,比如基于装饰器生成拦截代码,为不同的模块系统生成模块加载代码和解析JSX。但是,除了 Typescript 编译器之外,您可能还需要一个构建工具。例如,如果您想压缩代码,则必须向构建过程添加其他工具才能这样做。

There are TypeScript compilation plugins available for Webpack, Gulp, Gruntand pretty much any other JavaScript build tool out there. The TypeScript documentation has a section on integrating with build toolscovering them all. A linteris also available in case you would like even more build time checking. There are also a great number of seed projects out there that will get you started with TypeScript in combination with a bunch of other technologies like Angular 2, React, Ember, SystemJS, Webpack, Gulp, etc.

有适用于WebpackGulpGrunt和几乎所有其他 JavaScript 构建工具的TypeScript 编译插件。TypeScript 文档中有一个部分是关于涵盖所有这些的构建工具集成的部分。一个棉短绒也可如果你想更多的编译时间检查。还有大量的种子项目可以让你开始使用 TypeScript,结合其他一些技术,如 Angular 2、React、Ember、SystemJS、Webpack、Gulp 等。

JavaScript interoperability

JavaScript 互操作性

Since TypeScript is so closely related to JavaScript it has great interoperability capabilities, but some extra work is required to work with JavaScript libraries in TypeScript. TypeScript definitionsare needed so that the TypeScript compiler understands that function calls like _.groupByor angular.copyor $.fadeOutare not in fact illegal statements. The definitions for these functions are placed in .d.tsfiles.

由于 TypeScript 与 JavaScript 密切相关,因此它具有强大的互操作能力,但需要一些额外的工作才能在 TypeScript 中使用 JavaScript 库。打字稿定义需要这样的打字稿编译理解函数调用像_.groupBy或者angular.copy或者$.fadeOut不是真正意义上的非法语句。这些函数的定义放在.d.ts文件中。

The simplest form a definition can take is to allow an identifier to be used in any way. For example, when using Lodash, a single line definition file declare var _ : anywill allow you to call any function you want on _, but then, of course, you are also still able to make mistakes: _.foobar()would be a legal TypeScript call, but is, of course, an illegal call at run-time. If you want proper type support and code completion your definition file needs to to be more exact (see lodash definitionsfor an example).

定义可以采用的最简单形式是允许以任何方式使用标识符。例如,当使用Lodash 时,单行定义文件declare var _ : any将允许你调用任何你想要的函数_,但是,当然,你仍然会犯错误:_.foobar()这将是一个合法的 TypeScript 调用,但是,当然,运行时的非法调用。如果你想要适当的类型支持和代码完成,你的定义文件需要更精确(参见lodash 定义示例)。

Npm modulesthat come pre-packaged with their own type definitions are automatically understood by the TypeScript compiler (see documentation). For pretty much any other semi-popular JavaScript library that does not include its own definitions somebody out there has already made type definitions available through another npm module. These modules are prefixed with "@types/" and come from a Github repository called DefinitelyTyped.

带有自己的类型定义的预打包的Npm 模块会被 TypeScript 编译器自动理解(请参阅文档)。对于几乎所有其他不包含自己定义的半流行 JavaScript 库,有人已经通过另一个 npm 模块提供了类型定义。这些模块以“@types/”为前缀,来自于一个名为absoluteTyped的 Github 存储库。

There is one caveat: the type definitions must match the version of the library you are using at run-time. If they do not, TypeScript might disallow you from calling a function or dereferencing a variable that exists or allow you to call a function or dereference a variable that does not exist, simply because the types do not match the run-time at compile-time. So make sure you load the right version of the type definitions for the right version of the library you are using.

有一个警告:类型定义必须与您在运行时使用的库版本相匹配。如果没有,TypeScript 可能会禁止您调用函数或取消引用存在的变量,或者允许您调用函数或取消引用不存在的变量,仅仅是因为类型在编译时与运行时不匹配. 因此,请确保为您正在使用的库的正确版本加载正确版本的类型定义。

To be honest, there is a slight hassle to this and it may be one of the reasons you do not choose TypeScript, but instead go for something like Babel that does not suffer from having to get type definitions at all. On the other hand, if you know what you are doing you can easily overcome any kind of issues caused by incorrect or missing definition files.

说实话,这有点麻烦,这可能是你不选择 TypeScript 的原因之一,而是选择像 Babel 这样的东西,它根本不需要获得类型定义。另一方面,如果您知道自己在做什么,就可以轻松克服由不正确或丢失定义文件引起的任何类型的问题。

Converting from JavaScript to TypeScript

从 JavaScript 转换为 TypeScript

Any .jsfile can be renamed to a .tsfile and ran through the TypeScript compiler to get syntactically the same JavaScript code as an output (if it was syntactically correct in the first place). Even when the TypeScript compiler gets compilation errors it will still produce a .jsfile. It can even accept .jsfiles as input with the --allowJsflag. This allows you to start with TypeScript right away. Unfortunately, compilation errors are likely to occur in the beginning. One does need to remember that these are not show-stopping errors like you may be used to with other compilers.

任何.js文件都可以重命名为.ts文件并通过 TypeScript 编译器运行,以在语法上获得与输出相同的 JavaScript 代码(如果它首先在语法上是正确的)。即使 TypeScript 编译器出现编译错误,它仍然会生成一个.js文件。它甚至可以接受.js带有--allowJs标志的文件作为输入。这使您可以立即开始使用 TypeScript。不幸的是,编译错误很可能在一开始就发生。确实需要记住,这些不是像您在其他编译器中可能习惯的那样显示停止错误。

The compilation errors one gets in the beginning when converting a JavaScript project to a TypeScript project are unavoidable by TypeScript's nature. TypeScript checks allcode for validity and thus it needs to know about all functions and variables that are used. Thus type definitions need to be in place for all of them otherwise compilation errors are bound to occur. As mentioned in the chapter above, for pretty much any JavaScript framework there are .d.tsfiles that can easily be acquired with the installation of DefinitelyTyped packages. It might, however, be that you've used some obscure library for which no TypeScript definitions are available or that you've polyfilled some JavaScript primitives. In that case, you must supply type definitions for these bits for the compilation errors to disappear. Just create a .d.tsfile and include it in the tsconfig.json's filesarray, so that it is always considered by the TypeScript compiler. In it declare those bits that TypeScript does not know about as type any. Once you've eliminated all errors you can gradually introduce typing to those parts according to your needs.

将 JavaScript 项目转换为 TypeScript 项目时,一开始会出现编译错误,这是 TypeScript 的性质无法避免的。TypeScript 检查所有代码的有效性,因此它需要了解所有使用的函数和变量。因此,所有这些都需要类型定义,否则必然会发生编译错误。如上一章所述,对于几乎任何 JavaScript 框架,都.d.ts可以通过安装绝对类型包轻松获取文件. 然而,这可能是因为您使用了一些没有可用 TypeScript 定义的晦涩库,或者您已经对一些 JavaScript 原语进行了 polyfill。在这种情况下,您必须为这些位提供类型定义以消除编译错误。只需创建一个.d.ts文件并将其包含在 tsconfig.json 的files数组中,以便 TypeScript 编译器始终考虑它。在其中将 TypeScript 不知道的那些位声明为 type any。一旦您消除了所有错误,您就可以根据您的需要逐渐向这些部分引入输入。

Some work on (re)configuring your build pipeline will also be needed to get TypeScript into the build pipeline. As mentioned in the chapter on compilation there are plenty of good resources out there and I encourage you to look for seed projects that use the combination of tools you want to be working with.

还需要在(重新)配置构建管道方面进行一些工作,以使 TypeScript 进入构建管道。正如在编译一章中提到的,那里有很多好的资源,我鼓励您寻找使用您想要使用的工具组合的种子项目。

The biggest hurdle is the learning curve. I encourage you to play around with a small project at first. Look how it works, how it builds, which files it uses, how it is configured, how it functions in your IDE, how it is structured, which tools it uses, etc. Converting a large JavaScript codebase to TypeScript is doable when you know what you are doing. Read this blog for example on converting 600k lines to typescript in 72 hours). Just make sure you have a good grasp of the language before you make the jump.

最大的障碍是学习曲线。我鼓励你首先尝试一个小项目。看看它是如何工作的,它是如何构建的,它使用哪些文件,它是如何配置的,它如何在你的 IDE 中运行,它是如何构建的,它使用哪些工具等等。当你知道将一个大型 JavaScript 代码库转换为 TypeScript 时是可行的你在做什么。阅读此博客,例如在 72 小时内将 60 万行转换为打字稿)。在进行跳转之前,请确保您对语言有很好的掌握。

Adoption

采用

TypeScript is open-source (Apache 2 licensed, see GitHub) and backed by Microsoft. Anders Hejlsberg, the lead architect of C# is spearheading the project. It's a very active project; the TypeScript team has been releasing a lot of new features in the last few years and a lot of great ones are still planned to come (see the roadmap).

TypeScript 是开源的(Apache 2 许可,请参阅GitHub)并由 Microsoft 提供支持。C# 的首席架构师Anders Hejlsberg是该项目的带头人。这是一个非常活跃的项目;在过去的几年里,TypeScript 团队已经发布了很多新功能,并且仍然计划推出很多很棒的功能(请参阅路线图)。

Some facts about adoption and popularity:

关于采用和受欢迎程度的一些事实:

  • In the 2017 StackOverflow developer surveyTypeScript was the most popular JavaScript transpiler (9th place overall) and won third place in the most loved programming language category.
  • In the 2018 state of js surveyTypeScript was declared as one of the two big winners in the JavaScript flavors category (with ES6 being the other).
  • In the 2019 StackOverlow deverloper surveyTypeScript rose to the 9th place of most popular languages amongst professional developers, overtaking both C and C++. It again took third place amongst most the most loved languages.

回答by lebobbi

TypeScript does something similar to what less or sass does for CSS. They are super sets of it, which means that every JS code you write is valid TypeScript code. Plus you can use the other goodies that it adds to the language, and the transpiled code will be valid js. You can even set the JS version that you want your resulting code on.

TypeScript 的作用类似于 less 或 sass 对 CSS 的作用。它们是它的超级集,这意味着您编写的每个 JS 代码都是有效的 TypeScript 代码。另外,您可以使用它添加到语言中的其他好处,并且转换后的代码将是有效的 js。您甚至可以设置您希望生成代码的 JS 版本。

Currently TypeScript is a super set of ES2015, so might be a good choice to start learning the new js features and transpile to the needed standard for your project.

当前 TypeScript 是 ES2015 的超级集,因此可能是开始学习新的 js 功能并转换为项目所需标准的不错选择。

回答by Dimitre Novatchev

"TypeScript Fundamentals" -- a Pluralsight video-course by Dan Wahlinand John Papais a really good, presently (March 25, 2016) updated to reflect TypeScript 1.8, introduction to Typescript.

TypeScript Fundamentals”—— Dan WahlinJohn Papa的 Pluralsight 视频课程非常好,目前(2016 年 3 月 25 日)更新以反映 TypeScript 1.8,Typescript 介绍。

For me the really good features, beside the nice possibilities for intellisense, are the classes, interfaces, modules, the ease of implementing AMD, and the possibility to use the Visual Studio Typescript debugger when invoked with IE.

对我来说,除了智能感知的不错可能性之外,真正好的特性是接口模块、易于实现 AMD,以及在用 IE 调用时使用 Visual Studio Typescript 调试器的可能性。

To summarize: If used as intended, Typescript can make JavaScript programming more reliable, and easier. It can increase the productivity of the JavaScript programmer significantly over the full SDLC.

总结:如果按预期使用,Typescript 可以使 JavaScript 编程更可靠、更容易。与完整的 SDLC 相比,它可以显着提高 JavaScript 程序员的生产力。

回答by Mayank Jain

Ecma script 5 (ES5) which all browser support and precompiled. ES6/ES2015 and ES/2016 came this year with lots of changes so to pop up these changes there is something in between which should take cares about so TypeScript.

所有浏览器都支持和预编译的 Ecma 脚本 5 (ES5)。ES6/ES2015 和 ES/2016 今年带来了很多变化,所以为了弹出这些变化,中间有一些东西应该注意 TypeScript。

? TypeScript is Types -> Means we have to define datatype of each property and methods. If you know C# then Typescript is easy to understand.

? TypeScript 是 Types -> 意味着我们必须定义每个属性和方法的数据类型。如果您了解 C#,那么 Typescript 很容易理解。

? Big advantage of TypeScript is we identity Type related issues early before going to production. This allows unit tests to fail if there is any type mismatch.

? TypeScript 的一大优势是我们可以在投入生产之前及早识别 Type 相关问题。如果有任何类型不匹配,这允许单元测试失败。