Javascript 如何使用流类型执行写运行时类型检查表达式?
假设我在Flow中定义了两种类型:Javascript 如何使用流类型执行写运行时类型检查表达式?,javascript,flowtype,Javascript,Flowtype,假设我在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; }; const f = o => { if (typeof(o.x) !== 'undef
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;
};
const f = o => {
if (typeof(o.x) !== 'undefined') {
return o.x;
}
return o.y;
};
如何实现isa A
我想创建一个表达式,在运行时根据流类型定义检查对象
编译后的代码可能如下所示:
const f = (o : A | B) : string => {
if (o isa A) { // Not real code
return o.x;
}
return o.y;
};
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
是字符串的对象”,而不是“只有y
是字符串的对象”
要获得预期的行为,需要使用流作为
现在说到第二点,最简单的方法是
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清楚地知道,属性存在的两种情况是可以返回字符串的唯一两种情况。这里有两个主要问题
没有什么规定B
类型的对象也不能有x
属性,就像a
一样,反之亦然
Flow不够聪明,无法以这种方式区分对象类型
首先,要明确的是,您现有的定义与
var o: B = {
x: 45,
y: "string",
};
因为{y:string}
表示“其中y
是字符串的对象”,而不是“只有y
是字符串的对象”
要获得预期的行为,需要使用流作为
现在说到第二点,最简单的方法是
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清楚地知道,属性存在的两种情况是唯一可以返回字符串的两种情况。这是一个非常好的答案,因为它触及了问题的根源。谢谢这是一个非常好的答案,因为它触及了问题的根源。谢谢