4

Is there a way to make TypeScript throw an error on an implicit type conversion? Seems to me like all the implicit type conversions in JavaScript are one of the larger sources of bugs in the language, so I'd like a way for something like the following code:

let h = (n: number): number => {
    let f = () => 0 
    return -f
}

to let me know it will be implicitly converting the function type to a number via the - operator, and thus always returning NaN.

Chandan Rauniyar
  • 814
  • 1
  • 14
  • 24
Jackson
  • 559
  • 7
  • 20
  • Does your example not even emit a warning? – stealththeninja Nov 18 '17 at 02:56
  • No warning, even with all flags I know of enabled. – Jackson Nov 18 '17 at 03:29
  • Just opened [Microsoft/TypeScript#20131](https://github.com/Microsoft/TypeScript/issues/20131) to get an answer to this, since I too am surprised that TS would be so lax here. – jcalz Nov 18 '17 at 15:05
  • @jcalz the accepted answer provides some insight as to why this might be desirable. I know TS was designed to not have a ton of errors when attempting to verify existing code, so that could be part of why that made this decision. Still annoying, so I’m going to extend tslint with a rule to check for this as eslint’s no-implicit-coercion does. Saw you work at IS&T btw. Hello from a current 2019 :) – Jackson Nov 18 '17 at 21:52

1 Answers1

0

TypeScript allows this because it is valid JavaScript. You can always override the toString() method.

Consider the following:

let x = {}
x.toString = () => "1"
ley y = -x  // -1

let f = () => { }
f.toString = () => "1"
let z = -f // -1
unional
  • 14,651
  • 5
  • 32
  • 56
  • 2
    I understand that it is valid JS, but so are a lot of things TS warns on. – Jackson Nov 18 '17 at 04:48
  • I understand that this could be surprising, but I think this fall into "do no harm" category. TypeScript can't detect the type otherwise (if you have implemented `toString()` and return a value that can/cannot be parsed to a number). You can try opening an issue at github, but likely it will be consider as "work as intended"). My two cents. – unional Nov 18 '17 at 05:24
  • Yeah I get that TS is working as intended. I was more looking for some external way I could check this. eslint has no-implicit-coercion, but there’s no tslint equivalent. And the extensions I found for adding eslint features to tslint didn’t implement no-implicit-coercion. Maybe I’ll have to just make it myself. Or settle for not having it. – Jackson Nov 18 '17 at 05:59