gpt4 book ai didi

javascript - 在 Flow 中精炼混合到已知对象类型

转载 作者:行者123 更新时间:2023-11-30 08:26:13 25 4
gpt4 key购买 nike

我们正在尝试在 Flow 中进行类型优化,以防止值在外部接口(interface)进入我们的应用程序。为此,我们使用 mixed,然后尝试细化为已知类型,但 Flow 并不容易!

下面看起来应该可行,我已经验证了 mixed 类型值符合 response 类型的要求。

type Response = { head: string }

const refineToResponse = (value: mixed): ?Response => {
if (value
&& typeof value === "object"
&& typeof value.head === "string") {

return value;
}

return null;
};

但我只是收到一条非常无用的错误消息:

16:     return value;
^^^^^ object. This type is incompatible with the expected return type of
11: const refineToResponse = (value: mixed): ?Response => {
^^^^^^^^ object type

Property head is incompatible:

 11: const refineToResponse = (value: mixed): ?Response => {
^^^^^ mixed. This type is incompatible with
8: head: string
^^^^^^ string

编辑:

A link to the code on TryFlow .

最佳答案

那是不安全的。如果某物在运行时具有 string 类型,这并不意味着它具有相同的静态类型,例如它可能是一些枚举:'Foo' | 'Bar',因此将其设为 string 将允许不安全的突变。另一方面,它可以是 number | string,所以将来 head 真的可以变成数字或任何类型。

相反,您可以执行以下操作:

const refineToResponse = (value: mixed): ?Response => {   
if (value
&& typeof value === "object"
&& typeof value.head === "string") {

return { head: value.head };
}

return null;
};

关于javascript - 在 Flow 中精炼混合到已知对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45276951/

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