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

This seems to work in TypeScript too:

    class C {
        i: number | number[];

        constructor() {
            this.i = 0;
        }

        foo(): void {
            this.i = [];
        }

        bar(): number {
            if (typeof this.i === 'number') {
                this.foo();
                return this.i;
            }
            return 0;
        }
    }

    console.log(typeof new C().bar());
It seems to be a problem with "naked" type unions in general. It's unfortunate.


Agreed, but I've never found it to be especially problematic. The type checker still catches the vast majority of things you'd expect a type checker to catch.

If you want to be able to change the type of something at runtime, static analysis isn't always going to be able to have your back 100% of the time. Turns out that's a tradeoff that many are willing to make.


Yes, 100%. I believe that any new Python codebase should embrace typing as much as possible[1], and any JavaScript library should be TypeScript instead. A type system with holes like this is better than no type system.

[1] Unfortunately, many important 3rd party libraries aren't typed. I try to wrap them in type-safe modules or localise their use, but if your codebase is deeply dependent on them, this isn't always feasible.




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

Search: