Type refining an `any` type in flowtype

144 views Asked by At

I seem to be misunderstanding how flowtype refinements work (or maybe my Nuclide/Atom + Flow setup is being dumb). 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. I'd like to sanity check that it has the right form (e.g. that it has a string ip field). Nuclide however warns me that every use of json in the above code is "Not covered by flow", including the entire json.ip expression. Why is that? I would have expected the typeof check to refine the type of json.ip to string.

Is there another way to refine untyped values?

Edit: Here's a tryflow example of what I'm seeing.

1

There are 1 answers

1
vkurchatkin On BEST ANSWER

No, you can't refine 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:

const json: mixed = await resp.json()