首页 > 解决方案 > Flow: Why does `instanceof Type` fail?

问题描述

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?

标签: javascriptflowtype

解决方案


在您的示例中,Foo它只是一个 Flow 类型(从已编译的代码中剥离),但instanceof它是原生 JavaScript。

JavaScriptinstanceof通过检查对象是否是构造函数的实例来工作。它不知道您的 Flow 类型,也无法检查对象是否是该类型。

您可能想typeof改用。

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

推荐阅读