我似乎误解了流型细化的工作原理(或者我的核素/原子+流设置可能很愚蠢)。我想做如下的事情:
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.")
}
}
我正在从 API 端点获取一些 JSON,它的类型为 any
。我想检查它是否具有正确的形式(例如,它有一个字符串 ip
字段)。然而,Nuclide 警告我,上述代码中对 json
的每次使用都是“未被流程覆盖”,包括整个 json.ip
表达式。这是为什么?我希望 typeof
检查将 json.ip
的类型细化为 string
。
还有其他方法可以优化非类型化值吗?
编辑:这是一个 tryflow example我所看到的。
最佳答案
不,您无法优化任何
。您已经可以用它做任何事情了,那还有什么意义呢?
如果您希望 Flow 验证您的代码,您应该立即将您的 any
转换为 mixed
:
const json: mixed = await resp.json()
关于javascript - 类型细化 flowtype 中的 `any` 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41382172/