0

I'm using Typescript and Prettier and every time I cast something in the first line of the function Prettier puts a semicolon as a first character.

Why? It seems unnecessary. Am I wrong?

I read the Rationale but still I cannot understand why we need to put the first semicolon there.

Prettier 2.2.1 Playground link

--parser typescript
--no-semi

Input:

function example() {
(this as MyType).method() // useless semicolon will be placed here
;(f as any).y = fy // the semicolon here is ok
return f
}

Output:

function example() {
  ;(this as MyType).method() // useless semicolon here
  ;(f as any).y = fy // the semicolon here is ok
  return f
}

Expected behavior:

The first semicolon must not be put.

I opened an issue on the Prettier repo but they suggested I ask here.

***UPDATE:

If I use prettier defaults I have issues too, see this example:

Prettier 2.2.1 Playground link

--parser typescript

Input:

export function inputSelect(e: MouseEvent): void {
    console.log("Test this")
    (e.target as HTMLInputElement)?.select();
}

Output:

export function inputSelect(e: MouseEvent): void {
  console
    .log("Test this")(e.target as HTMLInputElement)
    ?.select();
}

Expected behavior:

It should put the semicolon at the end of the console.log().

Fred Hors
  • 941
  • 6
  • 28
  • 1
    It says why in that doc you link: *"It makes the line independent of other lines so you can move and add lines without having to think about ASI rules."* If you *did* insert a line before, the parentheses could get interpreted as *invoking* the result of the previous line. There is an example of this (with brackets not parentheses) in that documentation too. – jonrsharpe Mar 18 '21 at 10:41
  • Ok, but there is an issue also with Prettier defaults. I updated the question. – Fred Hors Mar 18 '21 at 10:51
  • 3
    That's not an issue with Prettier defaults, it's an issue with your code. **You** need to add a semicolon there, because ASI won't. Prettier formats the code you've written, the problem is that code doesn't do what you think it does. – jonrsharpe Mar 18 '21 at 10:56
  • Ok. Thanks. I learned something today. – Fred Hors Mar 18 '21 at 11:06
  • yes just like (function() {})() is a way to run a function JavaScript ASI assumes ()() means you want to create a function -- for all it (ASI) knows console.log() is generating a function and expecting e.target as its input. – Zargold Mar 18 '21 at 16:59
  • Does this answer your question? [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi) – thorn0 Mar 18 '21 at 18:50

0 Answers0