[英]Type refining an `any` type in flowtype
I seem to be misunderstanding how flowtype refinements work (or maybe my Nuclide/Atom + Flow setup is being dumb). 我似乎误解了流类型优化的工作原理(或者我的Nuclide / Atom + Flow设置很笨)。 I'd like to do something like the following:
我想做以下事情:
async function getIp(): Promise<string> {
const resp = await fetch('https://httpbin.org/ip')
const json = await resp.json() // `json: any` at this point
if (typeof json.ip === 'string') {
return json.ip
} else {
throw new Error("Weird response.")
}
}
I'm fetching some JSON from an API endpoint, and it has type any
. 我正在从API端点获取一些JSON,并且其类型为
any
。 I'd like to sanity check that it has the right form (eg that it has a string ip
field). 我想检查一下它是否具有正确的格式(例如,它具有字符串
ip
字段)。 Nuclide however warns me that every use of json
in the above code is "Not covered by flow", including the entire json.ip
expression. 但是Nuclide警告我,上面代码中对
json
每次使用都是“不被流覆盖的”,包括整个json.ip
表达式。 Why is that? 这是为什么? I would have expected the
typeof
check to refine the type of json.ip
to string
. 我本来希望
typeof
检查将json.ip
的类型json.ip
为string
。
Is there another way to refine untyped values? 还有另一种方法来细化未类型化的值吗?
Edit: Here's a tryflow example of what I'm seeing. 编辑:这是我所看到的一个tryflow示例 。
No, you can't refine any
. 不,您无法优化
any
。 You already can do anything with it, so what's the point? 您已经可以使用它进行任何操作,那有什么意义呢?
If you want Flow to verify your code you should immediately convert your any
to mixed
: 如果您想让Flow验证您的代码,则应立即将
any
转换为mixed
:
const json: mixed = await resp.json()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.