Skip to content

Improve ergonomics with regards to exactOptionalPropertyTypes #2457

@OliverJAsh

Description

@OliverJAsh

Description

When object properties in the schema are optional, like so:

    "/search/photos": {
      "get": {
        "parameters": [
          {
            "name": "orientation",
            "in": "query",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {}
      }
    },

… openapi-typescript will generate a type with optional properties, like so:

    "/search/photos": {
        get: {
            parameters: {
                query: {
                    orientation?: string;
                };
            };
        };
    };

When we later try to use this type e.g. using openapi-fetch, if exactOptionalPropertyTypes is enabled we will get an error when passing explicit undefined:

const fetch = (orientation: string | undefined) =>
  fetchUnsplash.GET('/search/photos', { params: {
    // Property 'query' is missing in type '{ orientation: string | undefined;
    // }' but required in type '{ orientation?: string; }'.
    query: {
      orientation,
    }
  }});

Proposal

Add | undefined to optional property types to allow explicit undefineds. For example:

-orientation?: string;
+orientation?: string | undefined;

This is also the approach taken by React types e.g. to allow className={stringOrUndefined}: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/0691ed151006d619a77d5ad8104d444906a99502/types/react/index.d.ts#L2670

Extra

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestopenapi-tsRelevant to the openapi-typescript library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions