json-schema-to-typescript icon indicating copy to clipboard operation
json-schema-to-typescript copied to clipboard

Nullable $ref

Open amh4r opened this issue 4 years ago • 2 comments

If I specify a property as "either a schema reference or null", the null type is ignore. For example, the following schemas:

components:
  schemas:
    Foo:
      type: object
      properties:
        bar:
          $ref: "#/components/schemas/Bar"
          nullable: true
      required:
        - bar
    Bar:
      type: object
      properties:
        baz:
          type: boolean

Generates the following models:

export interface Foo {
  bar: {
    baz?: boolean;
    [k: string]: unknown;
  };
  [k: string]: unknown;
}

export interface Bar {
  baz?: boolean;
  [k: string]: unknown;
}

But what I expected is the following:

export interface Foo {
  bar: Bar | null;
  [k: string]: unknown;
}

export interface Bar {
  baz?: boolean;
  [k: string]: unknown;
}

amh4r avatar Sep 20 '21 19:09 amh4r

I tried creating a normalizer, but it looks like interface referencing relies on object pointers.

This is my normalizer:

rules.set('Convert nullable -> anyOf', schema => {
  if (schema.nullable === true) {
    delete schema.nullable

    const copiedSchema = {...schema}

    delete copiedSchema.nullable

    schema.anyOf = [
      copiedSchema,
      {
        type: 'null',
      },
    ]

    Object.keys(schema).forEach(key => {
      if (key !== 'anyOf') {
        delete schema[key]
      }
    })
  }
})

But it creates this:

export interface Foo {
  bar: {
    baz?: boolean;
    [k: string]: unknown;
  } | null;
  [k: string]: unknown;
}

export interface Bar {
  baz?: boolean;
  [k: string]: unknown;
}

amh4r avatar Sep 20 '21 20:09 amh4r

#312

ondrej-111 avatar Mar 07 '22 10:03 ondrej-111