Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

typescript - When is it appropriate to use a semicolon?

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

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, D and all the other cases not covered by my example?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 for loops, but the .forEach method is 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.

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

*This returns the venerable 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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...