[英]How can I do a write run-time type-check expression using Flow type?
Suppose I have two types defined in Flow: 假设我在Flow中定义了两种类型:
type A = {
x : string;
};
type B = {
y : string;
};
Now I have a function f
like this: 现在我有一个函数
f
像这样:
const f = (o : A | B) : string => {
if (o isa A) { // Not real code
return o.x;
}
return o.y;
};
How do I implement o isa A
? 如何实施
o isa A
?
I want to create an expression that checks an object against a Flow type-definition at run-time. 我想创建一个表达式,在运行时根据Flow类型定义检查对象。
The compiled code might look like this: 编译后的代码可能如下所示:
const f = o => {
if (typeof(o.x) !== 'undefined') {
return o.x;
}
return o.y;
};
There are two primary issues here. 这里有两个主要问题。
B
-typed object can't have a x
property too, just like A
, and same for the inverse. B
型对象也不能具有x
属性,就像A
一样,反之亦然。 For the first point, to be clear, your existing definition is fine with 首先,要明确一点,您现有的定义适用于
var o: B = {
x: 45,
y: "string",
};
because { y: string }
means "an object where y
is a string
", not "an object with only a y
that is a string
." 因为
{ y: string }
意思是“其中y
是string
的对象”,而不是“ 仅 y
是string
的对象”。
To get the behavior you are expecting, you'd need to use Flow's Exact Object Syntax as 为了获得您期望的行为,您需要使用Flow的Exact Object Syntax作为
type A = {|
x : string;
|};
type B = {|
y : string;
|};
Now to the second point, the easiest approach is 现在到第二点,最简单的方法是
const f = (o : A | B) : string => {
if (typeof o.x !== "undefined") {
return o.x;
}
if (typeof o.y !== "undefined") {
return o.y;
}
throw new Error("Unreachable code path");
};
to make it clear to Flow that the two cases where the properties exist are the only two cases where a string can be returned. 为了使Flow清楚,只有两种可以返回字符串的情况,即存在属性的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.