typescript 什么时候使用分号合适?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38823062/
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-09-09 07:16:07  来源:igfitidea点击:

When is it appropriate to use a semicolon?

typescriptcoding-style

提问by ooxi

I know that JavaScript (and thus TypeScript) support the omission of semicolons in many cases. Nevertheless I want to add semicolons to be unambiguous as suggested in TypeScript Deep Dive

我知道 JavaScript(以及 TypeScript)在很多情况下都支持省略分号。不过,我想按照TypeScript Deep Dive 中的建议添加分号,使其明确无误

However I cannot find a guide that lists where to use semicolon. For example look at the following code

但是,我找不到列出在何处使用分号的指南。例如看下面的代码

class Person {
  private name: string; // A

  constructor(name: string) {
    this.name = name;
  }; // B

  public add = () => {
    return "C";
  }; // C
}; // D

I'm fairly sure to use a semicolon at A. But what about B, C, Dand all the other cases not covered by my example?

我相当确定在A使用分号。但是BCD以及我的示例未涵盖的所有其他情况呢?

I'm not asking where to omit semicolon but where to add them. An answer like alwaysdoes not fulfill my needs since I cannot add a ;after public. I want to know where exactly to put semicolon.

我不是问在哪里省略分号,而是在哪里添加它们。像总是一样的答案不能满足我的需求,因为我无法;public. 我想知道到底在哪里放分号。

采纳答案by Devin G Rhode

Just prefix lines starting with [, (, or ` with a semicolon and you're (almost) golden*

只需在以[,(或 `开头的行加上分号,你就(几乎)是金色的*

Using the same example as another answer:

使用与另一个答案相同的示例:

var x = { xx : "hello", yy : "world"}
(function () {
    console.log("Hello World");
})();

We add a semicolon according to this rule:

我们根据这个规则添加一个分号:

var x = { xx : "hello", yy : "world"}
;(function () {

otherwise javascript thinks we're trying to call(some function, or reference[some array. This is simpler, easier to follow, and it's visually easier to spot. You also need semicolons in forloops, but the .forEachmethodis a cleaner and easier method. I'd confidently say this one rule covers 99% of the scenarios you need to use a semicolon in javascript/typescript.

否则 javascript 认为我们正在尝试call(某个函数或reference[某个数组。这更简单,更容易遵循,并且在视觉上更容易发现。您还需要在for循环中使用分号,但该.forEach方法是一种更简洁、更简单的方法。我可以自信地说,这条规则涵盖了 99% 需要在 javascript/typescript 中使用分号的场景。

Following this method, it's important to associate a newline with terminating a statement.

按照这种方法,将换行符与终止语句相关联很重要

*This returns the venerable undefined:

*这将返回可敬的undefined

  return 
          7

After return, there's a newline, and the browser inserts a semicolon, terminating the statement like this:

返回后,有一个换行符,浏览器插入一个分号,像这样终止语句:

  return; // this will return undefined.
          7

Do this instead:

改为这样做:

  return (
          7
  )

Javascript is actually pretty smart with semicolons, there's an open paren, so no semicolon is inserted until the closing paren is found.

Javascript 使用分号实际上非常聪明,有一个开放括号,所以在找到结束括号之前不会插入分号。

If you have a habit of putting semicolons everywhere and not knowing exactly when they are needed, you could read this for a several page long explanation: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding

如果您习惯于在任何地方放置分号并且不知道确切何时需要它们,您可以阅读这篇长达几页的解释:http: //blog.izs.me/post/2353458699/an-open-letter-to -javascript-leaders-关于

I admit most people will still just litter semi colons at the end of every line, but if you're new and just learning, this is the better approach.

我承认大多数人仍然会在每一行的末尾乱丢分号,但如果你是新手并且刚刚学习,这是更好的方法。

回答by Scott Willeke

Like some other modern languagesderived from the C syntax, JavaScript syntax was designedto allow you to omit semicolons in almost all situations. I'd say use them always or use them never*. To use them "never" the long and short of it is that every statement goes on a new line and never begin a line with (, [, or `.

其他一些源自 C 语法的现代语言一样,JavaScript 语法旨在允许您在几乎所有情况下省略分号。我会说总是使用它们或从不使用它们*。为“从不”的长期和短期使用它们的它是每个语句那张新的生产线,从来没有开始符合([`

However, to use them "never", you should definitely be using a linter such as JavaScript Standard Styleor the eslint built-in semi rulewhich will make sure that you avoid the few gotchas such as the following:

但是,要“从不”使用它们,您绝对应该使用诸如JavaScript 标准样式eslint 内置 semi 规则之类的linter,这将确保您避免以下几个问题:

a = b + c
(d + e).foo()

The above is interpreted as a = b + c(d + e).foo();Note that by following the above rule and not beginning a line with (this situation is prevented.

以上解释为a = b + c(d + e).foo();请注意,通过遵循上述规则并且不以(这种情况开始行是可以防止的。

Another common example is the following:

另一个常见的例子如下:

return
{
     hello: "world"
};

At a glance one may think this will be interpreted as returning an object, but it actually interpreted as return;and the code to define the object after the return statement is unreachable. Again, by following the rule of not beginning a line with {this is avoided.

乍一看,这会被解释为返回一个对象,但它实际上被解释为return;并且返回语句后定义对象的代码不可达。同样,通过遵循不以{this开头的规则,可以避免。



  • *Okay, okay, not never, but almost never.
  • *好吧,好吧,不是从不,而是几乎从不。

回答by Dylan Meeus

TL;DR: Always

TL;DR:总是

Keep in mind: better safe than sorry

请记住:安全总比后悔好

You should probably place them all the time. You don't needto place them in order for TypeScript to work, but you will avoid errors by doing so. ASI (Automatic Semicolon Insertion) works quite well most of time, but not always. Do you really want to run into a problem just because you didn't put a semicolon, and you keep overlooking the mistake? (Depending on your IDE, the mistake might actually be caught). But consider this perfectly valid Javascript.

您可能应该一直放置它们。你并不需要将它们放置,以便打字稿工作,但你会这样做避免错误。ASI(自动分号插入)在大多数情况下都能很好地工作,但并非总是如此。你真的想因为没有加分号而遇到问题,并且一直忽略错误吗?(根据您的 IDE,实际上可能会发现错误)。但是考虑一下这个完全有效的 Javascript。

 var x = { xx : "hello", yy : "world"}
 (function () {
     console.log("Hello World");
 })();

This is valid javascript (and thus valid typescript). This code will actually give an error. Uncaught TypeError: (intermediate value)(intermediate value) is not a function(…).

这是有效的 javascript (因此有效的打字稿)。这段代码实际上会出错。Uncaught TypeError: (intermediate value)(intermediate value) is not a function(…).

Which could be avoided by just placing a semicolon after the first line. You don't need it there, and if the next line wasn't that function line, it would probably work correctly. But you want to take that risk? It seems like taking the risk for mistakes over one extra character is not worth it to me. Plus, after a while, you just get used to place semicolons at the end of a line anyway;

这可以通过在第一行后放置一个分号来避免。你不需要它,如果下一行不是那个函数行,它可能会正常工作。但是你想冒这个险吗?对我来说,为一个额外的角色冒犯错误的风险似乎不值得。另外,过了一段时间,你就习惯了在行尾放置分号;

Think of your colleagues

想想你的同事

Another reason you might want to use them all the time is in the case of code changing. Your colleague might have to change your code - and in doing so thinks that the ASI will keep working even with his code change. Imagine that this is not the case, and that his change actually makes ASI do something wrong. Is it really worth that headache for your colleague? If he changes enough of your code and then suddenly runs into a lot of errors, he might be rather confused if he does not know the exact way in which ASI is working. You could save a potential colleague quite a bit of (unneccessary) work by just putting them everywhere.

您可能希望一直使用它们的另一个原因是在代码更改的情况下。您的同事可能不得不更改您的代码 - 这样做会认为即使他的代码更改,ASI 也会继续工作。想象一下,事实并非如此,他的改变实际上让ASI做错了。让你的同事头疼真的值得吗?如果他对您的代码进行了足够多的更改,然后突然遇到很多错误,如果他不知道 ASI 的确切工作方式,他可能会感到非常困惑。只需将潜在同事放在任何地方,您就可以为潜在同事节省大量(不必要的)工作。

回答by Rick O'Shea

You need to watch that you do not inadvertently add semi-colons but the best way to avoid that self-inflicted bug is not to use them except where required by the language.

您需要注意不要无意中添加了分号,但是避免这种自我造成的错误的最佳方法是不要使用它们,除非语言要求。

This bug is as likely as the one and only case where omitting semicolons might not capture your actual intent:

此错误与省略分号可能无法捕捉到您的实际意图的唯一情况一样可能:

for(int i = 0; i < count; i++); do()

for(int i = 0; i < 计数; i++); 做()

There is one situation where your intent might be ambiguous, with the unusual style of starting a line with a (or a [character, since the newline doesn't terminate the statement in that case. The vast majority of the time it's precisely what you want, it's obvious when it's not, and you can dream up some statements with or without semicolons (as I showed above) that are problematic.

在一种情况下,您的意图可能不明确,以([字符开始一行的不寻常风格,因为在这种情况下换行符不会终止语句。绝大多数情况下,这正是您的意思想要,当它不是时很明显,你可以想象一些有问题的带有或不带有分号的语句(如我上面所示)。

I'm not going to say it's irrational to use semicolons because it is so ingrained in the culture, but please ignore the irrational fear many attempt to support with a convoluted and inaccurate discussion of ASI or mad hand waving. It's pure dogma, friends.

我不会说使用分号是不合理的,因为它在文化中根深蒂固,但请忽略许多人试图通过对 ASI 或疯狂挥手的令人费解和不准确的讨论来支持的非理性恐惧。这是纯粹的教条,朋友们。