javascript - 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?
解决方案
在您的示例中,Foo
它只是一个 Flow 类型(从已编译的代码中剥离),但instanceof
它是原生 JavaScript。
JavaScriptinstanceof
通过检查对象是否是构造函数的实例来工作。它不知道您的 Flow 类型,也无法检查对象是否是该类型。
您可能想typeof
改用。
function func(o: Foo | string) {
if (typeof o === 'string') {
console.log(o);
} else {
console.log(o.a);
}
}
推荐阅读
- ldap - 用于查看器配置文件过滤器的气流 ldap 组设置
- python - 更改 PyQt5 的调色板
- python - 无法调用函数以使退出框出现在pygame中
- javascript - 如何让 Google 使用 history.pushState 索引我的页面?
- xml - 如何使用 VB.net 代码从 XML 文件创建 XSD 文件
- javascript - 在 AS3 中悬停时缩放
- php - 如何从以 .dll 结尾的外部 url 接收和解析 xml 请求
- c++ - 如何在类中为向量使用 () 初始化程序?
- azure - 函数“SignalR”的侦听器无法启动。Azure 函数与信号器绑定
- javascript - 选中复选框时如何显示/隐藏列