gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:27:10 26 4
gpt4 key购买 nike

假设我在 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 的对象”,而不是“仅具有 一个y,它是一个字符串。”

要获得您期望的行为,您需要使用 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 明确表示存在属性的两种情况是唯一可以返回字符串的两种情况。

关于javascript - 如何使用 Flow 类型编写运行时类型检查表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48662103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com