Skip to content

Awkward typing when response is undefined #2461

@vezaynk

Description

@vezaynk

openapi-fetch version

0.14.0

Description

I ran into a breaking change due to the change in #1968

Previously, my code had a condition like this for handling invalid flows:

const fetchResponse: FetchResponse<T, Options, Media> = promise;

const { data, error, response } = await promise;

if (data) {
   return data; // typed as ParseAsResponse<SuccessResponse<ResponseObjectMap<T>, Media>, Options>
} else {
  throw new Error()
}

This worked fine as long as empty responses were not treated as undefined.

Now that data can be undefined for valid responses, I had to adjust my code a bit:

if (response.ok) {
  // ParseAsResponse<SuccessResponse<ResponseObjectMap<T>, Media>, Options> | undefined
   return data;
} else {
  throw new Error()
}

But this broke the type contract, because now data isn't T anymore, it's T | undefined. This has downstream consequences of a propagating undefined which isn't intended.

For the moment, I fixed it with an as cast, but I'm thinking ideally, this would be handled by refining based on response.ok alone.

Secondly, there is a broader issue when doing this, in that it breaks react-query's queryFn, since undefined is not a valid return value: TanStack/query#4964

Can it default to null instead of undefined ?

Reproduction

n/a

Expected result

n/a

Extra

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingopenapi-fetchRelevant to the openapi-fetch library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions