Re:How an Anti-TypeScript “JavaScript developer” like me bec...
by toolslive on Tuesday March 02, 2021 @03:05PM
(#26319861)
TypeScript is definitely an improvement over pure Javascript. However, you can still lie about the types and it still allows you to write nonsense (even in pure TS).
will compile without any problems
[ Parent
| on HN ]
Re:How an Anti-TypeScript “JavaScript developer” like me bec...
by curtisf on Tuesday March 02, 2021 @03:55PM
(#26320562)
TypeScript _does_ detect some such impossible conditions (like `x === 1`), so this omission is intentional.
I think this is partly necessitated by one particularly large soundness hole in TypeScript, which is that expressions are typed as though dictionary and array subscripts are always in bounds:
function foo(arr: number[]) {
const m: number = arr[3]; // typechecks
if (m === undefined) {
// this IS reachable
console.log("arr does not contain key `[3]`");
}
}
The alternative would be forcing all array and record accesses to have type `whatever | undefined`, despite the fact that almost all such accesses are clearly in bounds.This is in fact now a part of TypeScript behind a flag since 4.1: https://devblogs.microsoft.com/typescript/announcing-typescr...
Adding a compile-time bounds-checker to TypeScript to find cases where the `| undefined` is unnecessary would definitely be helpful and interesting, but would do nothing to help TypeScript's reputation of being difficult to wield and slow to compile.
It's also not an easy problem to solve, due to the semantics of JavaScript arrays:
let a = [];
a[5] = "five";
console.log(a.length); // 6
console.log(a[4]); // undefined (!)
Re:How an Anti-TypeScript “JavaScript developer” like me bec...
by toolslive on Wednesday March 10, 2021 @02:57AM
(#26408919)
you're right about the dictionary lookup possibly being undefined (and the compiler flag there). Some people (including me) would really appreciate a `--hindley-milner-type-inference` compiler flag.
Re:How an Anti-TypeScript “JavaScript developer” like me bec...
by mschuetz on Tuesday March 02, 2021 @03:30PM
(#26320205)
That example looks like a strawman to me. In practice, x would probably originate from outside the function, as a parameter or class member, and there is a good chance it could hold the value null or undefined. Seems like way too much additional work with little to no benefit to make the compiler track things like that through the whole application. Worse, the variable state could intentionally be hardcoded to try things and it would be weird if the compiler would error because the variable is never set to undefined, when I might be hardcoding it to undefined later on.