繁体   English   中英

如何使用Flow类型执行写运行时类型检查表达式?

[英]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;
};

这里有两个主要问题。

  1. 没有什么说过B型对象也不能具有x属性,就像A一样,反之亦然。
  2. Flow不够智能,无法通过这种方式区分对象类型。

首先,要明确一点,您现有的定义适用于

var o: B = {
  x: 45,
  y: "string",
};

因为{ y: string }意思是“其中ystring的对象”,而不是“ ystring的对象”。

为了获得您期望的行为,您需要使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM