Flow: Why does `instanceof Type` fail?

use*_*006 3 javascript flowtype

I seriously cannot think of a more basic use case of Union types than this:

test.js

// @flow
type Foo = {
  a: string,
  b: number
}

function func(o: Foo | string) {
  if (o instanceof Foo) {            // <<<<< ERROR
    console.log(o.a);
  } else {
    console.log(o);
  }
}
Run Code Online (Sandbox Code Playgroud)

Flow gives me an error on the line:

o instanceof Foo
Run Code Online (Sandbox Code Playgroud)

with this:

Cannot reference type Foo [1] from a value position.
Run Code Online (Sandbox Code Playgroud)

What am I doing wrong and how do I make this logic work?

Ale*_*ara 5

In your example, Foo is just a Flow type (which gets stripped from compiled code), but instanceof is native JavaScript.

JavaScript's instanceof works by checking if an object is an instance of a constructor function. It has no knowledge of your Flow types, and cannot check if an object is that type.

You might want to use typeof instead.

function func(o: Foo | string) {
  if (typeof o === 'string') {
    console.log(o);
  } else {
    console.log(o.a);
  }
}
Run Code Online (Sandbox Code Playgroud)