json-schema-to-typescript
json-schema-to-typescript copied to clipboard
Nullable $ref
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;
}
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;
}
#312