Skip to content

If error responses do not declare a content type, then success responses can be typed as undefined. #2350

Open
@dwjohnston

Description

@dwjohnston

openapi-fetch version

0.14.0

Description

In a scenario where error response do not have content shapes defined, then the type narrowing behaviour for success responses stops working correctly and can show as undefined.

Reproduction

I have a reproduction for this here:

https://github.com/dwjohnston/openapi-typescript-example/tree/missing-error-data

I have an spec defines the response for GET /pets/{petId} that looks like this:

                "responses": {
                    "200": {
                        "description": "successful operation",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/Pet"
                                }
                            }
                        }
                    },
                    "500": {
                        "description": "Invalid ID supplied"
                    }
                },

Note no content is defined for the error response.

This will generate typings like this:

        responses: {
            /** @description successful operation */
            200: {
                headers: {
                    [name: string]: unknown;
                };
                content: {
                    "application/json": components["schemas"]["Pet"];
                };
            };
            /** @description Invalid ID supplied */
            500: {
                headers: {
                    [name: string]: unknown;
                };
                content?: never;
            };
        };

When I use the typings with OpenPI fetch then :

async function getPetById(id: number) : Promise< components["schemas"]["Pet"]>{
    const result= await client.GET("/pet/{petId}", {
        "params": {
            "path" :{
                "petId": id
            }
        }
    });

    
    
    if (result.error) {
        console.error("Error fetching pets:", result.error);
        throw new Error(result.error);
    }

    
    // Data can be undefined
    return result.data;
}

Expected result

Given the type guard where we have removed the error scenarios, the result.data type should definitely exist.

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