4 ms·
A bunch of the issues here are due to the author actually casting instead of letting inference do its job. // unsound, val.toFixed(0) compiles let val: n
by akdor1154 7y ago
A bunch of the issues here are due to the author actually casting instead of letting inference do its job.
// unsound, val.toFixed(0) compiles
let val: number = ("string" as string | number)
vs.
// sound, val.toFixed(0) does not compile
let val = ("string" as string | number) // sound
In general, it's unnecessary (and as demonstrated, potentially harmful) to annotate assignments like these.
- TheDong 7y agoTheir example without `: number` still exhibits the exact same behaviour. The `: number` isn't a cast either, it's declaring the type of the variable. You can't help but explicitly name the type of a variable in many cases. What if they were passing val to a function as an argument? You can't have 'function foo(x)', you have to have 'function foo(x: number)' and name the type. So yes, their example is contrived, but no, what you said is not sound. It has the same problem as the one the author mentions. The typescript compiler intentionally does not catch their issue. If I'm misunderstanding what you're trying to demonstrate, please make a typescript playground of it.