[英]How can I do a write run-time type-check expression using Flow type?
假设我在Flow中定义了两种类型:
type A = {
x : string;
};
type B = {
y : string;
};
现在我有一个函数f
像这样:
const f = (o : A | B) : string => {
if (o isa A) { // Not real code
return o.x;
}
return o.y;
};
如何实施o isa A
?
我想创建一个表达式,在运行时根据Flow类型定义检查对象。
编译后的代码可能如下所示:
const f = o => {
if (typeof(o.x) !== 'undefined') {
return o.x;
}
return o.y;
};
这里有两个主要问题。
B
型对象也不能具有x
属性,就像A
一样,反之亦然。 首先,要明确一点,您现有的定义适用于
var o: B = {
x: 45,
y: "string",
};
因为{ y: string }
意思是“其中y
是string
的对象”,而不是“ 仅 y
是string
的对象”。
为了获得您期望的行为,您需要使用Flow的Exact Object Syntax作为
type A = {|
x : string;
|};
type B = {|
y : string;
|};
现在到第二点,最简单的方法是
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");
};
为了使Flow清楚,只有两种可以返回字符串的情况,即存在属性的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.