Reputation: 459
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);
}
}
Flow gives me an error on the line:
o instanceof Foo
with this:
Cannot reference type Foo [1] from a value position.
What am I doing wrong and how do I make this logic work?
Upvotes: 3
Views: 1475
Reputation: 60597
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);
}
}
Upvotes: 5