Skip to content

Nullable components with required values in complex schema types #497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
tompuric opened this issue Feb 28, 2023 · 1 comment
Open

Nullable components with required values in complex schema types #497

tompuric opened this issue Feb 28, 2023 · 1 comment

Comments

@tompuric
Copy link

Release 10.0.2 (#419) added the UtilRequiredKeys type that produces invalid generated code when you have a schema with complex schema types (anyOf/allOf/oneOf) that reference required fields of nullable components.

How to trigger in a schema:

  • Have a nullable component (myObject is the schema below)
  • Reference component with complex schema type (TestObject in the schema below)
  • Mark a nested field as required ("required": ["name"], as marked in TestObject)

Example schema:

{
  "openapi": "3.0.2",
  "info": {
    "title": "Nullable Refs Example",
    "version": "1.0.0"
  },
  "components": {
    "schemas": {
      "myObject": {
        "type": "object",
        "nullable": true,
        "properties": {
          "name": {
            "type": "string"
          }
        },
        "required": ["name"]
      },
      "TestObject": {
        "required": ["name"],
        "type": "object",
        "allOf": [
          {
            "$ref": "#/components/schemas/myObject"
          }
        ]
      }
    }
  }
}

Generated code from schema (utilising the nullable-3.0 test setup)

type UtilRequiredKeys<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;

export type MyObject = {
  name: string;
} | null;

export type TestObject = UtilRequiredKeys<MyObject, "name">;

Which produces the following error

Type 'string' does not satisfy the constraint 'never'.ts(2344)

Potential workarounds:

  • Adjust schema to avoid this scenario
  • remove usage of UtilRequiredKeys via the configuration.internalTemplateOptions.addUtilRequiredKeysType
  • override UtilRequiredKeys definition in template to handle null case via ts NonNullable
@romulof
Copy link

romulof commented Apr 9, 2025

Replacing it with this solved my problem:

type UtilRequiredKeys<T, K extends keyof NonNullable<T>> = T extends null
  ? never
  : Omit<NonNullable<T>, K> & Required<Pick<NonNullable<T>, K>>;

Still running more tests to check possible side-effects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants