4 ms·
it drives me absolutely insane that this TypeScript compiles: const num: number = [][0]
by dwhitney 6y ago
it drives me absolutely insane that this TypeScript compiles:
const num: number = [][0]
- smlckz 6y agoHuh, go figure the following: const a = 'this is not a ' + typeof + 'number'; Or JSFuck[1] in that matter. [1]: http://jsfuck.com http://jsfuck.com
- panzerklein 6y agoIt won't with --noUncheckedIndexedAccess on.
- wutbrodo 6y agoThat seems like a pretty insane default. Do you happen to know what the thinking is? While I'm fortunate enough to have never needed to spend significant time working in JS and its spawn, I've heard a lot of good things from people I respect about TS and its incremental typing approach, so I'm starting from the baseline assumption that this is a reasonable choice.
- ygra 6y agoThere seem to have been a few options that are disabled by default and emit additional errors, that slowly get turned on by default in later versions. Perhaps this is one of them.
- wutbrodo 6y agoThat's reasonable, thanks for the info
- panzerklein 6y agoThis option is too extreme to be enabled by default. Even --strict shortcut that turns on a bunch of useful checks does not include it.
- dtwhitney 6y agoYou can have all the internet points for today
- saurik 6y agoFWIW, most (arguably any/all) non-dependently-typed languages would let that slide, as [] is of type "array of (at best) X (which could be inferred as number by working backwards from the declaration)" and one of the operations you can do on an array is to index it, by a (maybe unsigned) integer, with 0 (either way) thereby being a valid index. For this to fail, in addition to the type of the array being parameterized by its size (which is at least not too uncommon if not exactly common) the type of that index operator has to be (more notably) at least parameterized by the concrete value 0 if not the abstract expression 0 (which would let you use a proof assistant to verify it for non-constant cases).
- Measter 6y agoWhile not a dependently-typed language, the Rust compiler can do this here for arrays. Arrays in Rust have the length as part of their type, which is compile-time constant, and if you're indexing with another compile-time constant the compiler will check it. So for a line: let number: i32 = [][0]; The compiler knows the array is 0-length, therefore the index is out of bounds, and emits this error: error: this operation will panic at runtime --> src/main.rs:2:23 | 2 | let number: i32 = [][0]; | ^^^^^ index out of bounds: the length is 0 but the index is 0 | = note: `#[deny(unconditional_panic)]` on by default Of course, it's trivial to defeat by converting the array to a slice first, then you get a runtime error. As an aside, am I the only one who got Four Candles'd by that title?