Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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 (!)


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: