Skip to content

Flow doesn't detect exhaustive type refinement #451

@samwgoldman

Description

@samwgoldman

In the example below, flow infers ?string when the actual return type is string. This isn't so bad, because you can easily turn the last else if into an else and get the same refinement and the correct inferred return type.

There's no reason flow can't catch this, and even complain about subsequent code being dead. (Edit: There is a fairly good reason, which is that the type of abc might be something other than ABC at runtime, due to any or interaction with untyped code. It would be unfortunate if Flow told you to remove code which actually caused a runtime exception!)

This is a good issue for someone trying to get their hands dirty with the type checker internals. I'd be happy to help anyone get oriented around this code if they want to take it on, or else I'll look into it in a couple weeks.

class A {}
class B {}
class C {}

type ABC = A | B | C;

function f(abc: ABC): string {
    if (abc instanceof A) {
        return 'A result';
    } else if (abc instanceof B) {
        return 'B result';
    } else if (abc instanceof C) {
        return 'C result';
    }
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions