4 ms·
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
by toolslive 6y ago
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).
> const x = 'xxxx'
> if(x === undefined) {
> console.log('never happens')
> }
will compile without any problems
- mschuetz 6y agoThat 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.
- curtisf 6y agoTypeScript _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-typescript-4-1-beta/#no-unchecked-indexed-access 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 (!)
- toolslive 6y agoyou'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.