我什么时候应该使用TypeScript?

by Alex Ewerlöf

由AlexEwerlöf

我什么时候应该使用TypeScript? (When should I use TypeScript?)

This article is now available in Japanese and Chinese.

该文章现已提供日文中文版本

Last summer we had to convert a huge code base (18,000+ lines of code) from JavaScript to TypeScript. I learned a lot about the strengths and weaknesses of each, and when it makes sense to use one over the other.

去年夏天,我们不得不将庞大的代码库(超过18,000行代码)从JavaScript转换为TypeScript。 我学到了很多关于两者的优点和缺点的知识,以及在什么情况下可以使用一种优点。

什么时候可以使用TypeScript (When it makes sense to use TypeScript)

当您的代码库很大时 (When you have a large codebase)

When your codebase is huge, and more than one person works on the project, a type system can help you avoid a lot of common errors. This is especially true for single-page applications.

当您的代码库很大,并且有多个人在项目上工作时,类型系统可以帮助您避免许多常见错误。 对于单页应用程序尤其如此。

Any time one developer could introduce breaking changes, it’s generally good to have some sort of safety mechanism.

任何时候只要开发人员可以进行重大更改,拥有某种安全机制通常都是很好的。

The TypeScript transpiler reveals the most obvious mistakes — though it won’t magically eliminate the need for debugging.

TypeScript 编译器揭示了最明显的错误-尽管不会神奇地消除调试的需要。

If your codebase isn’t all that big, it probably doesn’t make sense to make it larger by adding type annotations. I’ve converted 180+ files from JavaScript to TypeScript, and in most cases it added roughly 30% to the total code size.

如果您的代码库不是那么大,那么通过添加类型注释使其变大可能就没有意义了。 我已经将180多个文件从JavaScript转换为TypeScript,在大多数情况下,它使总代码大小增加了大约30%。

当您的团队的开发人员已经习惯于静态类型的语言时 (When your team’s developers are already accustom to statically-typed languages)

If you or the majority of the team come from a strongly typed language like C# or Java, and don’t want to go all-in on JavaScript, TypeScript is a good alternative.

如果您或团队中的大多数人都来自强类型语言(例如C#或Java),并且不想全神贯注地使用JavaScript,那么TypeScript是一个不错的选择。

Even though I recommend learning Javascript thoroughly, there’s nothing preventing you from using TypeScript without knowing JavaScript. In fact, TypeScript was created by the same guy who made C#, so the syntaxes are similar.

即使我建议您彻底学习Javascript,也不会阻止您在不了解JavaScript的情况下使用TypeScript。 实际上,TypeScript是由制作C#的同一个人创建的,因此语法相似。

In my company, we had a team of C# developers who were coding a sophisticated desktop application in C# and WPF (which is basically a front end development tool for the desktop world). They were then asked to join a web project as full stack developers. So in short order, they were able to learn TypeScript for the front end, then leverage their C# knowledge for the back end.

在我的公司中,我们有一个由C#开发人员组成的团队,他们正在用C#和WPF (基本上是桌面世界的前端开发工具)编写复杂的桌面应用程序。 然后,他们被要求以全栈开发人员的身份加入一个Web项目。 这样一来,他们就可以在前端学习TypeScript,然后在后端学习C#知识。

TypeScript可以替代Babel (TypeScript can serve as a replacement for Babel)

The old Microsoft used to take standard tools — Java for example — and add proprietary non-standard features to them — in this case resulting in J++. Then they would try to force developers to choose between the two.

旧的Microsoft曾经采用标准工具(例如Java),并向它们添加了专有的非标准功能,在这种情况下产生了J ++。 然后他们将试图迫使开发人员在两者之间进行选择。

TypeScript is exactly the same approach — this time for JavaScript. By the way, this isn’t Microsoft’s first fork of JavaScript. In 1996, they forked JavaScript to create JScript.

TypeScript是完全相同的方法—这次是JavaScript。 顺便说一下,这不是MicrosoftJavaScript的第一个分支。 在1996年,他们分叉JavaScript来创建JScript

Though it’s is a less-common use case, it’s technically possible to transpile ES6 code into ES5 using the TypeScript transpiler. This is possible because ES6 is essentially a subset of TypeScript, and the TypeScript transpiler generates ES5 code.

尽管这是一种不太常见的用例,但使用TypeScript编译器将ES6代码转换为ES5在技术上是可行的。 这是可能的,因为ES6本质上是TypeScript的子集,并且TypeScript 编译器生成ES5代码。

Typescript’s transpiler generates pretty readable Javascript (EcmaScript 5) code as output. That was one of the reasons why the Angular 2 team chose TypeScript over Google’s own Dart language.

Typescript的翻译器会生成可读性强的Javascript(EcmaScript 5)代码作为输出。 这就是Angular 2团队选择TypeScript而不是Google自己的Dart语言的原因之一。

Also, TypeScript has some cool features that are not in ES6, like enums and the ability to initialize member variables in a constructor. I’m not a big fan of inheritance, but I find it useful to have the public, private, protected, and abstract keywords in classes. TypeScript has them and ES6 doesn’t.

另外,TypeScript具有ES6中没有的一些很酷的功能,例如枚举和在构造函数中初始化成员变量的功能。 我不是继承的忠实拥护者,但是我发现在类中使用public,private,protected和abstract关键字很有用。 TypeScript有它们,而ES6没有。

Our C# developers thought it was super amazing to be able to write a lambda function as the body of a method — which eliminated the headaches associated with the this keyword.

我们的C#开发人员认为,能够将lambda函数作为方法的主体来编写,这真是太了不起了-消除了与关键字相关的麻烦。

当库或框架推荐TypeScript时 (When a library or framework recommends TypeScript)

If you are using Angular 2 or another library that recommends TypeScript, go for it. Take a look at what these developers have to say after using Angular 2 for six months.

如果您使用的是Angular 2或其他推荐TypeScript的库,请使用它。 看看这些开发人员在使用Angular 2六个月后要说些什么

Just know that — even though TypeScript can use all JavaScript libraries out of the box — if you want good syntax errors, you’ll need to add the type definitions for those libraries externally. Fortunately the nice guys at DefinitelyTyped have built a community-driven repo with tooling for doing just that. But this is still one extra step when you’re setting up your project

只需知道-即使TypeScript可以立即使用所有JavaScript库-如果您希望获得良好的语法错误,则需要在外部添加这些库的类型定义。 幸运的是, DefinitelyTyped的好人已经建立了一个社区驱动的存储库,并带有用于执行此操作的工具。 但这仍是您设置项目时的又一步骤

(On a side note: for all you JSX fans, check out TSX.)

(附带说明:对于您所有的JSX粉丝,请查看TSX 。)

当您真正感到需要速度时 (When you really feel the need for speed)

This may come as a shock to you, but the TypeScript code can in some situations perform better than JavaScript. Let me explain.

这可能会让您感到震惊,但是TypeScript代码在某些情况下的性能可能比JavaScript更好。 让我解释。

In our JavaScript code, we had a lot of type checks. It was a MedTech app, so even a small error could be literally fatal if it wasn’t dealt with properly. So a lot of functions had statements like:

在我们JavaScript代码中,我们进行了很多类型检查。 这是一个MedTech应用程序,因此,如果处理不当,即使是很小的错误也可能致命。 因此,许多函数具有如下语句:

if(typeof name !== ‘string) throw ‘Name should be string’

With TypeScript, we could eliminate a lot of these type checks all together.

使用TypeScript,我们可以消除很多这些类型检查。

This especially showed its effect in parts of the code where we previously had a performance bottleneck, because we were able to skip a lot of unnecessary runtime type checking.

这尤其在我们先前存在性能瓶颈的代码部分中显示了其效果,因为我们能够跳过很多不必要的运行时类型检查。

那么什么时候没有Typescript更好呢? (So when are you better off without Typescript?)

当您负担不起额外的翻译税时 (When you can’t afford an extra transpilation tax)

There are no plans to support TypeScript natively in the browsers. Chrome did some experiment, but later cancelled support. I suspect this has something to do with unnecessary runtime overhead.

没有计划在浏览器中本地支持TypeScript。 Chrome浏览器做了一些实验 ,但后来取消了支持。 我怀疑这与不必要的运行时开销有关。

If someone wants training wheels, they can install them. But bikes shouldn’t come with permanent training wheels. This means that you will always have to transpile your TypeScript code before running it in a browser.

如果有人想要训练轮,他们可以安装它们。 但是自行车不应该带有永久性的训练轮。 这意味着您必须始终先转换您的TypeScript代码,然后才能在浏览器中运行它。

For standard ES6, it’s a whole different story. When ES6 is supported by most browsers, the current ES6 to ES5 transpilation will become unnecessary (update: yes indeed!).

对于标准ES6,情况则完全不同。 当大多数浏览器都支持ES6时 ,当前的从ES6到ES5的转换将不再必要(更新: 是的 !)。

ES6 is the biggest change to the JavaScript language, and I believe most programmers will just settle with it. But those brave few who want to try the next version of JavaScript’s experimental features, or the features not yet implemented on all browsers — they will need to transpile anyway.

ES6是JavaScript语言的最大变化,我相信大多数程序员都会对此感到满意。 但是那些勇于尝试下一个版本JavaScript实验性功能或尚未在所有浏览器中实现的功能的勇者很少,他们仍然需要进行转换。

Without transpilation, you just modify the file and refresh your browser. That’s it. No watching, transpiling on demand, or build system are necessary.

无需编译,您只需修改文件并刷新浏览器即可。 而已。 无需监视, 按需编译构建系统

If you choose TypeScript, you will end up doing some extra bookkeeping for the type definitions for your Javascript libraries and frameworks (by using DefinitelyTyped or writing your own type annotations). That’s something you wouldn’t need to do for a pure JavaScript projects.

如果选择TypeScript,最终将为Javascript库和框架的类型定义做一些额外的记账工作(通过使用DefinitelyTyped或编写自己的类型注释)。 对于纯JavaScript项目,这是不需要做的。

当您想要避免奇怪的调试边缘情况时 (When you want to avoid weird debugging edge cases)

Sourcemaps make it easier to debug Typescript, but the status quo is not perfect. There are really annoying and confusing edge cases.

Sourcemap使调试Typescript更容易,但现状并不完美。 确实有一些令人烦恼和令人困惑的边缘案例。

Also, there are some problems debugging the “this” keyword and properties attached to it (hint: “_this” works in most cases). That is because Sourcemaps currently don’t have a good support for variables — though this may change in the future.

此外,调试“ this”关键字及其附加的属性时也会遇到一些问题(提示:“ _ this”在大多数情况下有效)。 这是因为Sourcemaps当前对变量没有很好的支持-尽管将来可能会改变。

当您想要避免潜在的性能损失时 (When you want to avoid potential performance penalties)

In our project, we had 9,000+ lines of good old ES5 JavaScript that delivered pure horse power to a 3D WebGL canvas. We kept it that way.

在我们的项目中,我们有9,000多行优质的旧ES5 JavaScript,它们向3D WebGL画布提供了纯马力。 我们保持这种方式。

The TypeScript transpiler (just like Babel) has features that require generating extra code (inheritance, enum, generics, async/await, etc). No matter how good your transpiler is, it can’t surpass the optimizations of a good programmer. So we decided to keep it in plain ES5 for ease of debug and deployment (no transpilation whatsoever).

TypeScript编译器(就像Babel一样)具有需要生成额外代码(继承,枚举,泛型,异步/等待等)的功能。 无论您的编译器多么出色,它都无法超越优秀程序员的优化。 因此,我们决定将其保留在纯ES5中,以简化调试和部署(不进行任何转换)。

That being said, the performance penalty is probably negligible compared to benefits of a type system and more modern syntax for most projects. But there are cases where milliseconds and even microseconds matter, and in those cases transpilation of any kind is not recommended (even with Babel, CoffeeScript, Dart, etc.).

话虽这么说,对于大多数项目而言,与类型系统和更现代的语法相比,性能损失可能微不足道。 但是在某些情况下,毫秒甚至微秒很重要,在这种情况下,建议不要进行任何形式的转换(即使使用Babel,CoffeeScript,Dart等也是如此)。

Note that Typescript doesn’t add any extra code for runtime type checking. All the type checking happens at transpile time and the type annotations are removed from the generated Javascript code.

请注意,Typescript不会为运行时类型检查添加任何额外的代码。 所有类型检查都在转换时进行,并且类型注释已从生成的Javascript代码中删除。

当您想最大化团队的敏捷性时 (When you want to maximize your team’s agility)

It’s quicker to set up something in JavaScript. The lack of a type system makes for agility and ease of changing stuff. It also makes it easier to break things, so make sure you know what you’re doing.

使用JavaScript设置内容更快。 缺少类型系统使敏捷性和更改内容变得容易。 这也使打破事情变得更加容易,因此请确保您知道自己在做什么。

Javascript is more flexible. Remember one of the main use cases for a type system is to make it hard to break stuff. If Typescript is Windows, Javascript is Linux.

Javascript更灵活。 请记住,类型系统的主要用例之一是使内容难以破解。 如果Typescript是Windows,则Javascript是Linux。

In JavaScript Land, you don’t get the training wheels of a type system, and the computer assumes you know what you’re doing, but allows you to ride much faster and maneuver easier.

在JavaScript Land中,您不会获得类型系统的训练轮,并且计算机会假定您知道自己在做什么,但可以让您骑行更快,更轻松。

This is particularly important to note if you’re still in the prototyping phase. If so, don’t waste your time with TypeScript. JavaScript is so much more flexible.

如果您仍处于原型制作阶段,则要特别注意这一点。 如果是这样,请不要浪费时间使用TypeScript。 JavaScript更加灵活。

Remember that TypeScript is a superset of JavaScript. This means that you can easily convert JavaScript to TypeScript later if you need to.

请记住,TypeScript是JavaScript的超集。 这意味着您以后可以根据需要轻松地将JavaScript转换为TypeScript。

我对JavaScript VS TypeScript的偏爱 (My preference on JavaScript VS TypeScript)

There is no one best language overall. But for each individual project, there is probably one objectively best language and library and framework and database and operating system and… you get the picture.

总体上没有一种最好的语言。 但是对于每个单独的项目,可能都有一种客观上最好的语言,库,框架,数据库和操作系统,并且……您可以理解。

For our project it made sense to use TypeScript. I tried to refactor some of my hobby projects to TypeScript but it did not worth the effort.

对于我们的项目,使用TypeScript是有意义的。 我试图将我的一些爱好项目重构为TypeScript,但这并不值得。

I personally like 5things about TypeScript:

我个人喜欢有关TypeScript的5件事:

  1. It’s fully compatible with ES6. It is really nice seeing Microsoft playing fair with the other browsers. Our ecosystem can benefit from a strong rival to Google, Mozilla, and Apple. Microsoft is spending serious energy on it — such as writing Visual Studio Code from scratch using TypeScript on Google Chrome, of all platforms.

    与ES6完全兼容。 很高兴看到Microsoft与其他浏览器公平竞争。 我们的生态系统可以从与Google,Mozilla和Apple的强大竞争对手中受益。 微软为此花费了大量精力,例如在所有平台上使用TypeScript在Google Chrome上从头开始编写Visual Studio代码

  2. The type system is optional. Coming from a C and Java background, I found the lack of type system in JavaScript liberating. But I hated losing time when I encountered stupid bugs during runtime. TypeScript allows me to avoid many common bugs so I can focus my time on fixing the real tricky ones. It’s a good balance. I like it. It’s my taste. I use types whenever I can because it gives me peace of mind. But that’s me. If I use TypeScript, I don’t want to limit myself to its ES6 features.

    类型系统是可选的。 来自C和Java背景,我发现JavaScript解放中缺乏类型系统。 但是我讨厌在运行时遇到愚蠢的错误而浪费时间。 TypeScript使我避免了许多常见的错误,因此我可以将时间集中在修复真正棘手的错误上。 这是一个很好的平衡。 我喜欢。 这是我的口味。 我会尽可能使用类型,因为它使我省心。 就是我 如果我使用TypeScript,则不想将自己局限于其ES6功能。
  3. The JavaScript code that comes out of the TypeScript transpiler is very readable. I am not a fan of Sourcemaps, so I do most of my debugging on the generated JavaScript. It’s absolutely awesome. I can totally understand why Angular 2 chose TypeScript over Dart.

    来自TypeScript编译器JavaScript代码非常易读。 我不是Sourcemaps的粉丝,因此我会在大多数生成JavaScript上进行调试。 绝对很棒 我完全理解为什么Angular 2 选择TypeScript而不是Dart

  4. TypeScript’s development experience is fantastic. VS Code is very smart when dealing with JavaScript (some may argue it’s the smartest JS IDE). But TypeScript pushes the limits to a whole new level. The autocompletion and refactoring features in VSCode work much more accurately, and it’s not because the IDE is super smart. That’s all thanks to TypeScript.

    TypeScript的开发经验很棒。 VS Code在处理JavaScript时非常聪明(有人可能会说这是最聪明的JS IDE)。 但是TypeScript将限制推向了一个全新的水平。 VSCode中的自动补全和重构功能可以更准确地工作,这并不是因为IDE超级智能。 这一切都要归功于TypeScript。

  5. The type annotations are like a basic level documentation. They declare the type of data that each function expects, their results and various other hints like readonly , publicor private attributes. In my experience, trying to refactor a JavaScript code to TypeScript, I usually end up with cleaner code with nicer structure. In fact writing TypeScript has improved how I write plain JavaScript.

    类型注释类似于基本级别的文档。 它们声明每个函数期望的数据类型,它们的结果以及各种其他提示,例如readonlypublicprivate属性。 以我的经验,尝试将JavaScript代码重构为TypeScript,我通常会得到结构更好的更干净的代码。 实际上,编写TypeScript改善了我编写普通JavaScript的方式。

Typescript is not the answer for everything. You can still write terrible code in it.

打字稿不能解决所有问题。 您仍然可以在其中编写可怕的代码

TypeScript haters are gonna hate, either because of fear of change or because they know somebody who knows somebody who is afraid of it. Life goes on and TypeScript introduces new features to its community anyway.

讨厌TypeScript的人会讨厌,要么是因为害怕改变,要么是因为他们认识某个人,而这个人知道害怕它的人。 生活还在继续,TypeScript还是向其社区引入了新功能

But like React, TypeScript is one of those influential technologies that is pushing the boundaries of our web development.

但是像React一样,TypeScript是推动我们Web开发边界的那些有影响力的技术之一。

Whether you use TypeScript or not, it doesn’t hurt to try it out in order to develop your own opinions on it. It has a learning curve, but if you already know JavaScript, it will be a smooth one.

不管您是否使用TypeScript,尝试对其提出自己的意见都没有什么害处。 它有一个学习曲线,但是如果您已经了解JavaScript,那将是一个平稳的过程。

Here is an online realtime TS transpiler with some examples that let you compare TypeScript code with its equivalent JavaScript code.

这是一个在线实时TS编译器 ,其中包含一些示例,可让您将TypeScript代码与其等效JavaScript代码进行比较。

Here is a quick tutorial, and a very nice guide, but I’m more a language-reference kinda guy. If you like video, here’s a course from Udemy.

这是一个快速的教程 ,一个非常好的指南 ,但是我还是一个语言参考的家伙。 如果您喜欢视频,这是Udemy的课程

John Papa has a a short article about ES5 and TypeScript.

John Papa有一篇关于ES5和TypeScript 的简短文章

There’s an interesting study that shows all things equal, a type system reduces bugs by 15%.

一项有趣的研究表明,所有事物都是平等的,类型系统将错误减少了15%。

Oh, and if you feel like going on a side mission, read why programming is the best job ever.

哦,如果您想执行附带任务,请阅读为什么编程是有史以来最好的工作

Liked what you read? Follow me to be notified when I write something new.

⚡️ 喜欢你读的书? 当我写新东西时,请跟随我以得到通知。

翻译自: https://www.freecodecamp.org/news/when-should-i-use-typescript-311cb5fe801b/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值