什么是TypeScript?为什么我要用它代替JavaScript? [关闭]

本文翻译自:What is TypeScript and why would I use it in place of JavaScript? [closed]

Closed . 已关闭 This question needs to be more focused . 这个问题需要更加集中 It is not currently accepting answers. 它当前不接受答案。

Want to improve this question? 想改善这个问题吗? Update the question so it focuses on one problem only by editing this post . 更新问题,使其仅通过编辑此帖子来关注一个问题。

Closed 2 years ago . 2年前关闭。

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或可用的库无法执行的工作是什么,这使我有理由考虑?


#1楼

参考:https://stackoom.com/question/rGQU/什么是TypeScript-为什么我要用它代替JavaScript-关闭


#2楼

I originally wrote this answer when TypeScript was still hot-off-the-presses. 我最初是在TypeScript仍然热销时写这个答案的。 Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth 五年后,这是一个不错的概述,但请查看以下Lodewijk的答案以获取更多深度

1000ft view... 1000英尺查看...

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. TypeScript是JavaScript的超集,主要提供可选的静态类型,类和接口。 One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code . 最大的好处之一是使IDE能够提供更丰富的环境,以便在键入代码时发现常见错误。

To get an idea of what I mean, watch Microsoft's introductory video on the language. 要了解我的意思,请观看有关该语言的Microsoft入门视频

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. 它是开源的,但是如果您使用受支持的IDE,则只有在键入时才能获得聪明的Intellisense。 Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza ). 最初,这只是Microsoft的Visual Studio(也在Miguel de Icaza的博客文章中提到)。 These days, other IDEs offer TypeScript support too . 如今其他IDE也提供TypeScript支持

Are there other technologies like it? 还有其他类似的技术吗?

There's CoffeeScript , but that really serves a different purpose. CoffeeScript ,但这确实有不同的用途。 IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). 恕我直言,CoffeeScript为人类提供了可读性,但TypeScript还通过其可选的静态类型为工具提供了深层的可读性(有关更多批评,请参阅此最新博客文章 )。 There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code ) 还有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. 注意TypeScript如何定义成员变量和类方法参数的类型。 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. 转换为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 调试TypeScript

Many browsers and IDEs offer direct debugging support through sourcemaps. 许多浏览器和IDE通过Sourcemap提供直接调试支持。 See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio 有关更多详细信息,请参见此堆栈溢出问题: 使用Visual Studio调试TypeScript代码

Want to know more? 想知道更多?

I originally wrote this answer when TypeScript was still hot-off-the-presses. 我最初是在TypeScript仍然热销时写这个答案的。 Check out Lodewijk's answer to this question for some more current detail. 查看Lodewijk对这个问题的答案,以获取更多当前的详细信息。


#3楼

" TypeScript Fundamentals " -- a Pluralsight video-course by Dan Wahlin and John Papa is a really good, presently (March 25, 2016) updated to reflect TypeScript 1.8, introduction to Typescript. TypeScript基础知识 ” - 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. 总结 :如果按预期使用TypeScript,可以使JavaScript编程更可靠,更容易。 It can increase the productivity of the JavaScript programmer significantly over the full SDLC. 在整个SDLC上,它可以显着提高JavaScript程序员的生产率。


#4楼

TypeScript's relation to JavaScript TypeScript与JavaScript的关系

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript - typescriptlang.org . 打字稿是一个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. JavaScript是由EMCA技术委员会39开发的一种编程语言,该委员会由许多不同的利益相关者组成。 TC39 is a committee hosted by ECMA : an internal standards organization. TC39是ECMA主办的委员会:内部标准组织。 JavaScript has many different implementations by many different vendors (eg Google, Microsoft, Oracle, etc.). JavaScript由许多不同的供应商(例如Google,Microsoft,Oracle等)具有许多不同的实现。 The goal of JavaScript is to be the lingua franca of the web. 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. TypeScript是JavaScript语言的超集,具有单个开源编译器,并且主要由单个供应商Microsoft开发。 The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient. 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 ECMAScript standards. 对现代JavaScript功能的支持 -JavaScript语言(不是运行时)通过ECMAScript标准进行了标准化。 Not all browsers and JavaScript runtimes support all features of all ECMAScript standards (see this overview ). 并非所有的浏览器和JavaScript运行时都支持所有ECMAScript标准的所有功能(请参阅此概述 )。 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 targets under the --target compiler option). TypeScript允许使用许多最新的ECMAScript功能,并将其转换为您选择的较旧的ECMAScript目标(请参阅--target编译器选项下的编译目标列表)。 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. 这意味着您可以安全地使用新功能,例如模块,lambda函数,类,扩展运算符和解构,同时保持与旧版浏览器和JavaScript运行时的向后兼容性。

  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. 高级类型系统 -类型支持不是ECMAScript标准的一部分,并且可能永远不会由于JavaScript的解释性质而不是编译性质而引起。 The type system of TypeScript is incredibly rich and includes: interfaces, enums, hybrid types, generics, union/intersection types, access modifiers and much more. TypeScript的类型系统非常丰富,包括:接口,枚举,混合类型,泛型,并集/交集类型,访问修饰符等等。 The official website of TypeScript gives an overview of these features. TypeScript的官方网站提供了这些功能的概述。 Typescript's type system is on-par with most other typed languages and in some cases arguably more powerful. Typescript的类型系统可与大多数其他类型的语言媲美,并且在某些情况下可以说更强大。

  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. 开发人员工具支持 -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的语言相比,TypeScript具有独特的理念。 JavaScript code is valid TypeScript code; JavaScript代码是有效的TypeScript代码; TypeScript is a superset of JavaScript. TypeScript是JavaScript的超集。 You can almost rename your .js files to .ts files and start using TypeScript (see "JavaScript interoperability" below). 您几乎可以将.js文件重命名为.ts文件,然后开始使用TypeScript(请参见下面的“ JavaScript互操作性”)。 TypeScript files are compiled to readable JavaScript, so that migration back is possible and understanding the compiled TypeScript is not hard at all. TypeScript文件被编译为可读的JavaScript,因此可以向后移植,并且理解编译的TypeScript一点也不困难。 TypeScript builds on the successes of JavaScript while improving on its weaknesses. 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. 一方面,您拥有使用现代ECMAScript标准并将其编译为较旧的JavaScript版本的面向未来的工具,其中Babel是最受欢迎的工具。 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 ). 另一方面,您所使用的语言可能与针对JavaScript的JavaScript完全不同,例如CoffeeScript,Clojure,Dart,Elm,Haxe,Scala.js,以及更多其他宿主(请参见此列表 )。 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. 这些语言虽然可能比JavaScript的未来可能会领先的地方要好,但冒着更大的风险,即找不到足够的采用以保证其未来。 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. 与JavaScript的互操作还可以更复杂一些,因为它们与JavaScript实际相去甚远。

TypeScript sits in between these two extremes, thus balancing the risk. TypeScript位于这两个极端之间,因此可以平衡风险。 TypeScript is not a risky choice by any standard. 从任何标准来看,TypeScript都不是冒险的选择。 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. 如果您不熟悉JavaScript,则只需花费很少的时间就可以习惯,因为它不是完全不同的语言,具有出色的JavaScript互操作性支持,并且最近已被广泛采用。

Optionally static typing and type inference 可选的静态类型和类型推断

JavaScript is dynamically typed. JavaScript是动态类型的。 This means JavaScript does not know what type a variable is until it is actually instantiated at run-time. 这意味着JavaScript在运行时实际实例化之前不知道变量的类型。 This also means that it may be too late. 这也意味着可能为时已晚。 TypeScript adds type support to JavaScript. TypeScript为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). 如果正确使用卡牌(由您输入代码的严格程度或完全由您键入代码来决定),则可以完全消除由错误假设某个变量属于某种类型而导致的错误。

TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. 通过使用类型推断,TypeScript使键入变得更容易,并且显式性更低。 For example: var x = "hello" in TypeScript is the same as var x : string = "hello" . 例如:TypeScript中的var x = "hello"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 is optionally typed by default. 默认情况下,可以选择键入TypeScript。 For example function divideByTwo(x) { return x / 2 } is a valid function in TypeScript which can be called with any kind of parameter, even though calling it with a string will obviously result in a runtime error. 例如, function divideByTwo(x) { return x / 2 }是TypeScript中的有效函数,可以使用任何类型的参数调用,即使使用字符串调用它显然会导致运行时错误。 Just like you are used to in JavaScript. 就像您已经习惯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 . 之所以行之有效,是因为当未明确分配任何类型并且无法推断类型时(例如在divideByTwo示例中),TypeScript将隐式分配类型any This means the divideByTwo function's type signature automatically becomes function divideByTwo(x : any) : any . 这意味着dividByTwo函数的类型签名会自动变为function divideByTwo(x : any) : any There is a compiler flag to disallow this behavior: --noImplicitAny . 有一个禁止该行为的编译器标志:-- --noImplicitAny Enabling this flag gives you a greater degree of safety, but also means you will have to do more typing. 启用此标志可以提高安全性,但也意味着您将不得不进行更多键入。

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 Github suggests 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. 这些语言包括C,C ++, JavaScript ,Objective-C,Php和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. Clojure,Haskell,Ruby,Scala和TypeScript等语言均具有负系数,这意味着这些语言导致缺陷修复提交的可能性低于平均值。

Enhanced IDE support 增强的IDE支持

The development experience with TypeScript is a great improvement over JavaScript. TypeScript的开发经验是对JavaScript的极大改进。 The IDE is informed in real-time by the TypeScript compiler on its rich type information. TypeScript编译器会根据其丰富的类型信息实时通知IDE。 This gives a couple of major advantages. 这提供了两个主要优点。 For example, with TypeScript, you can safely do refactorings like renames across your entire codebase. 例如,使用TypeScript,您可以安全地进行重构,例如在整个代码库中进行重命名。 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. 在您忙于编码时,编译错误将直接在IDE中以红色蠕变线报告。 All in all, this allows for a significant gain in productivity compared to working with JavaScript. 总而言之,与使用JavaScript相比,这可以显着提高生产率。 One can spend more time coding and less time debugging. 一个人可以花费更多的时间进行编码,而花费较少的调试时间。

There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio Code, WebStorm, Atom and Sublime. 有很多对TypeScript都具有出色支持的IDE,例如Visual Studio Code,WebStorm,Atom和Sublime。

Strict null checks 严格的空检查

Runtime errors of the form cannot read property 'x' of undefined or undefined is not a function are very commonly caused by bugs in JavaScript code. 形式的运行时错误cannot read property 'x' of undefinedundefined is not a function ,这通常是由JavaScript代码中的错误引起的。 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 any typed variables). 由于无法使用TypeScript编译器不知道的变量( any类型变量的属性除外),TypeScript可以立即降低发生此类错误的可能性。 It is still possible though to mistakenly utilize a variable that is set to undefined . 仍然有可能错误地利用设置为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. 但是,使用TypeScript 2.0版,可以通过使用非空类型来一起消除这些类型的错误。 This works as follows: 其工作原理如下:

With strict null checks enabled ( --strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. 启用严格的空检查( --strictNullChecks编译器标志)后,TypeScript编译器将不允许将undefined分配给变量,除非您明确声明其为可空类型。 For example, let x : number = undefined will result in a compile error. 例如, let x : number = undefined将导致编译错误。 This fits perfectly with type theory since undefined is not a number. 因为undefined不是数字,所以这与类型理论非常吻合。 One can define x to be a sum type of number and undefined to correct this: let x : number | undefined = undefined 可以将x定义为number的总和类型,然后将其undefinedundefined来纠正此问题: let x : number | undefined = undefined let x : number | undefined = undefined . 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 null or undefined , the TypeScript compiler can determine through control flow based type analysis whether or not your code can safely use a variable or not. 一旦已知类型为可为空,即它的类型也可以为nullundefined ,则TypeScript编译器可以通过基于控制流的类型分析来确定您的代码是否可以安全地使用变量。 In other words when you check a variable is undefined through for example an if statement 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. 换句话说,当您通过例如if语句检查变量是否undefined ,TypeScript编译器将推断出代码控制流的该分支中的类型不再可以为null,因此可以安全地使用。 Here is a simple example: 这是一个简单的示例:

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 Anders Hejlsberg的2016年会议联合设计师对此功能进行了详细说明和演示: 视频 (从44:30到56:30)。

Compilation 汇编

To use TypeScript you need a build process to compile to JavaScript code. 要使用TypeScript,您需要一个构建过程来编译为JavaScript代码。 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 ( --watch compiler flag) so that all subsequent changes can be compiled at greater speed. TypeScript编译器支持增量编译( --watch编译器标志),以便可以以更高的速度编译所有后续更改。

The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. TypeScript编译器可以在生成的.js文件中内联源地图信息,或创建单独的.map文件。 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. 调试实用程序(例如Chrome DevTools和其他IDE)可以使用源地图信息,以将JavaScript中的行与在TypeScript中生成它们的行相关联。 This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code. 这使您可以在运行时直接在TypeScript代码上设置断点和检查变量。 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. 源地图信息的效果很好,距TypeScript尚有很长时间,但调试TypeScript通常不如直接使用JavaScript那样好。 Take the this keyword for example. this关键字为例。 Due to the changed semantics of the this keyword around closures since ES2015, this may actually exists during runtime as a variable called _this (see this answer ). 由于自ES2015以来闭包周围的this关键字的语义已更改, this在运行时此变量实际上可能作为名为_this的变量存在(请参阅此答案 )。 This may confuse you during debugging but generally is not a problem if you know about it or inspect the JavaScript code. 这可能会在调试过程中使您感到困惑,但是如果您了解或检查JavaScript代码,通常不会出现问题。 It should be noted that Babel suffers the exact same kind of issue. 应当指出,巴别塔也遭受同样的问题。

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 . TypeScript编译器还可以完成其他一些技巧,例如基于装饰器生成拦截代码,为不同模块系统生成模块加载代码以及解析JSX However, you will likely require a build tool besides the Typescript compiler. 但是,除了Typescript编译器之外,您可能还需要构建工具。 For example, if you want to compress your code you will have to add other tools to your build process to do so. 例如,如果要压缩代码,则必须在构建过程中添加其他工具。

There are TypeScript compilation plugins available for Webpack , Gulp , Grunt and pretty much any other JavaScript build tool out there. 有TypeScript编译插件可用于WebpackGulpGrunt以及几乎所有其他JavaScript构建工具。 The TypeScript documentation has a section on integrating with build tools covering them all. TypeScript文档中有一节介绍如何涵盖所有内容的构建工具集成 A linter is also available in case you would like even more build time checking. 如果您想要更多的构建时间检查,也可以使用lint 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. 还有大量的种子项目,可以带您开始使用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与JavaScript紧密相关,因此具有强大的互操作性功能,但是要使用TypeScript中的JavaScript库,还需要做一些额外的工作。 TypeScript definitions are needed so that the TypeScript compiler understands that function calls like _.groupBy or angular.copy or $.fadeOut are not in fact illegal statements. 需要TypeScript定义 ,以便TypeScript编译器理解_.groupByangular.copy$.fadeOut类的函数调用实际上并非非法语句。 The definitions for these functions are placed in .d.ts files. 这些功能的定义位于.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 _ : any will 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. 例如,当使用Lodash时 ,单个行定义文件declare var _ : any将允许您调用_想要的任何函数,但是,当然,您仍然会犯错误: _.foobar()会是合法的TypeScript调用,但在运行时当然是非法的调用。 If you want proper type support and code completion your definition file needs to to be more exact (see lodash definitions for an example). 如果您需要适当的类型支持和代码完成功能,则您的定义文件需要更加精确(有关示例,请参见lodash定义 )。

Npm modules that come pre-packaged with their own type definitions are automatically understood by the TypeScript compiler (see documentation ). TypeScript编译器会自动理解预先打包有自己的类型定义的Npm模块 (请参阅文档 )。 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. 对于几乎任何其他不包含自己的定义的半流行JavaScript库,已经有人通过另一个npm模块提供了类型定义。 These modules are prefixed with "@types/" and come from a Github repository called DefinitelyTyped . 这些模块以“ @ types /”为前缀,并来自名为DefinitelyTyped的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. 如果不存在,TypeScript可能会禁止您调用函数或取消引用存在的变量,或者允许您调用函数或取消引用不存在的变量,仅因为类型与编译时的运行时不匹配。 So make sure you load the right version of the type definitions for the right version of the library you are using. 因此,请确保为所使用的库的正确版本加载正确的类型定义版本。

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. 老实说,这样做有点麻烦,这可能是您不选择TypeScript的原因之一,而是选择了Babel之类的东西,而该东西完全不需要获取类型定义。 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. 另一方面,如果您知道自己在做什么,则可以轻松解决由于定义文件不正确或丢失而引起的任何类型的问题。

Converting from JavaScript to TypeScript 从JavaScript转换为TypeScript

Any .js file can be renamed to a .ts file 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). 任何.js文件都可以重命名为.ts文件,并通过TypeScript编译器运行,以在语法上获得与输出相同的JavaScript代码(如果从语法上说正确的话)。 Even when the TypeScript compiler gets compilation errors it will still produce a .js file. 即使TypeScript编译器遇到编译错误,它仍然会生成.js文件。 It can even accept .js files as input with the --allowJs flag. 它甚至可以通过--allowJs标志接受.js文件作为输入。 This allows you to start with TypeScript right away. 这使您可以立即从TypeScript开始。 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. 确实需要记住,这些并不是停止显示的错误,就像您可能习惯于其他编译器一样。

The compilation errors one gets in the beginning when converting a JavaScript project to a TypeScript project are unavoidable by TypeScript's nature. TypeScript的性质不可避免地会在将JavaScript项目转换为TypeScript项目时开始出现编译错误。 TypeScript checks all code for validity and thus it needs to know about all functions and variables that are used. TypeScript检查所有代码的有效性,因此需要了解所有使用的函数和变量。 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.ts files that can easily be acquired with the installation of DefinitelyTyped packages . 如上一章所述,对于几乎所有JavaScript框架,都有.d.ts文件,可以通过安装DefinitelyTyped包轻松获取。 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. 但是,可能是因为您使用了一些晦涩的库,而其中没有TypeScript定义可用,或者您已经填充了一些JavaScript原语。 In that case, you must supply type definitions for these bits for the compilation errors to disappear. 在这种情况下,必须为这些位提供类型定义,以使编译错误消失。 Just create a .d.ts file and include it in the tsconfig.json's files array, so that it is always considered by the TypeScript compiler. 只需创建一个.d.ts文件并将其包含在tsconfig.json的files数组中,以便TypeScript编译器始终考虑该文件。 In it declare those bits that TypeScript does not know about as type any . 在其中将TypeScript不知道的那些位声明为any类型。 Once you've eliminated all errors you can gradually introduce typing to those parts according to your needs. 消除所有错误后,您可以根据需要逐步在这些部分中键入内容。

Some work on (re)configuring your build pipeline will also be needed to get TypeScript into the build pipeline. 为了使TypeScript进入构建管道,还需要进行一些(重新)配置构建管道的工作。 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. 正如在编译一章中提到的那样,那里有很多好的资源,我鼓励您寻找使用您要使用的工具组合的种子项目。

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. 看看它是如何工作的,它是如何构建的,它使用的是哪个文件,它是如何配置的,在IDE中是如何运行的,它是如何结构的,它使用的是什么工具等。将大型JavaScript代码库转换为TypeScript是可行的你在做什么。 Read this blog for example on converting 600k lines to typescript in 72 hours ). 阅读此博客,例如有关在72小时内将60万行转换为打字稿的信息 Just make sure you have a good grasp of the language before you make the jump. 进行跳跃之前,请确保您已掌握该语言。

Adoption 采用

TypeScript is open-source (Apache 2 licensed, see GitHub ) and backed by Microsoft. TypeScript是开源的(Apache 2许可,请参见GitHub ),并得到Microsoft的支持。 Anders Hejlsberg , the lead architect of C# is spearheading the project. C#的首席架构师Anders Hejlsberg负责该项目。 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团队已经发布了许多新功能,并且仍然计划推出许多出色的功能(请参阅路线图 )。

Some facts about adoption and popularity: 有关采用和普及的一些事实:

  • In the 2017 StackOverflow developer survey TypeScript was the most popular JavaScript transpiler (9th place overall) and won third place in the most loved programming language category. 2017年StackOverflow开发人员调查中, TypeScript是最受欢迎的JavaScript编译器(总体排名第9位),并在最受欢迎的编程语言类别中排名第三。
  • In the 2018 state of js survey TypeScript was declared as one of the two big winners in the JavaScript flavors category (with ES6 being the other). 2018年的js调查中, TypeScript被宣布为JavaScript风味类别的两个最大赢家之一(其中ES6是另一个)。
  • In the 2019 StackOverlow deverloper survey TypeScript rose to the 9th place of most popular languages amongst professional developers, overtaking both C and C++. 2019年StackOverlow deverloper调查中, TypeScript在专业开发人员中最受欢迎的语言排名上升至第9位,超过了C和C ++。 It again took third place amongst most the most loved languages. 在最受欢迎的语言中,它再次获得第三名。

#5楼

TypeScript does something similar to what less or sass does for CSS. TypeScript的作用类似于CSS的less或sass。 They are super sets of it, which means that every JS code you write is valid TypeScript code. 它们是它的超级集,这意味着您编写的每个JS代码都是有效的TypeScript代码。 Plus you can use the other goodies that it adds to the language, and the transpiled code will be valid js. 另外,您可以使用它添加到语言中的其他优点,并且转译后的代码将是有效的js。 You can even set the JS version that you want your resulting code on. 您甚至可以设置要在其上生成结果代码的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功能并转换为项目所需标准的一个不错的选择。


#6楼

Ecma script 5 (ES5) which all browser support and precompiled. 所有浏览器均支持并预先编译的Ecma脚本5(ES5)。 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. ES6 / ES2015和ES / 2016今年进行了很多更改,因此要弹出这些更改,请务必谨慎之间使用TypeScript。

• TypeScript is Types -> Means we have to define datatype of each property and methods. •TypeScript是类型->意味着我们必须定义每个属性和方法的数据类型。 If you know C# then Typescript is easy to understand. 如果您知道C#,那么Typescript很容易理解。

• Big advantage of TypeScript is we identity Type related issues early before going to production. •TypeScript的一大优势是我们可以在投入生产之前及早识别与类型相关的问题。 This allows unit tests to fail if there is any type mismatch. 如果类型不匹配,这会使单元测试失败。

发布了0 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/105199632