2
votes

This is a very stripped down version of our original code:

  const start: number = 10
  const end: number = 20
  (someElement as HTMLInputElement).setSelectionRange(start, end)

Then there was a nice little red squiggly line under the 20. Indicating this error: This expression is not callable Type 'Number' has no call signatures. We figured out the solution is to add a semicolon:

  const start: number = 10
  const end: number = 20;
  (someElement as HTMLInputElement).setSelectionRange(start, end)

Does anyone know why it would compile that way? I'm assuming typescript being compiled into javascript is interpreting that code as below and attempting to invoke the end variable as a function.

  const start: number = 10
  const end: number = 20(someElement as HTMLInputElement).setSelectionRange(start, end)
1

1 Answers

4
votes

This behavior isn't specific to TypeScript; the issue you're having is the same as you would get with plain JavaScript. The TypeScript compiler isn't choosing to compile correct TypeScript into incorrect JavaScript; instead, it's dutifully transpiling weird TypeScript into the equivalent weird JavaScript.

In general, automatic semicolon insertion doesn't apply if the next token after the line terminator is possibly syntactically valid, the only exceptions being one of the specific places where line terminators are forbidden (see the MDN link above for a list of these places). The open parenthesis ( after 20 can apparently be interpreted as the start of a function call, which is syntactically valid. And because a line terminator is not forbidden after 20, no semicolon gets inserted.

In TypeScript, you get a compiler error warning you that you are calling 20 which has no call signature. That error is a good thing, because it gives you a chance to fix your code by inserting your own semicolon, before you get to runtime. Because again, if you were writing the above code in plain JavaScript (e.g., without type assertions), the JavaScript runtime would interpret the code the same way and you'd get a runtime error instead of a compiler warning:

// This is plain JS, not TS 
try {
  const someElement = document.getElementsByTagName("input").item(0);
  const start = 10
  const end = 20
  (someElement).setSelectionRange(start, end)
} catch (e) {
  console.log("OOPS I CAUGHT AN ERROR");
  console.log(e.message); // 20 is not a function
}

If you run that code snippet (with no TypeScript compiler in sight) you'll see that your browser's JavaScript runtime issues a TypeError that 20 is not a valid function.