diff --git a/src/normalizer.ts b/src/normalizer.ts index 5549b59a..00b5fcff 100644 --- a/src/normalizer.ts +++ b/src/normalizer.ts @@ -222,6 +222,20 @@ rules.set('Transform const to singleton enum', schema => { } }) +rules.set('Transform nullable to null type', schema => { + if (schema.nullable !== true) { + return + } + + delete schema.nullable + + if (!schema.type) { + return + } + + schema.type = [...[schema.type].flatMap(value => value), 'null'] +}) + export function normalize( rootSchema: LinkedJSONSchema, dereferencedPaths: DereferencedPaths, diff --git a/test/__snapshots__/test/test.ts.md b/test/__snapshots__/test/test.ts.md index d9e34739..2a4a9f98 100644 --- a/test/__snapshots__/test/test.ts.md +++ b/test/__snapshots__/test/test.ts.md @@ -1791,6 +1791,24 @@ Generated by [AVA](https://avajs.dev). }␊ ` +## nullable.js + +> Expected output to match snapshot for e2e test: nullable.js + + `/* eslint-disable */␊ + /**␊ + * This file was automatically generated by json-schema-to-typescript.␊ + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,␊ + * and run json-schema-to-typescript to regenerate this file.␊ + */␊ + ␊ + export interface Nullable {␊ + foo?: string | null;␊ + bar?: string | number | null;␊ + [k: string]: unknown;␊ + }␊ + ` + ## oneOf.js > Expected output to match snapshot for e2e test: oneOf.js diff --git a/test/__snapshots__/test/test.ts.snap b/test/__snapshots__/test/test.ts.snap index cd1fb9ed..a424806a 100644 Binary files a/test/__snapshots__/test/test.ts.snap and b/test/__snapshots__/test/test.ts.snap differ diff --git a/test/e2e/nullable.ts b/test/e2e/nullable.ts new file mode 100644 index 00000000..2faa5e8f --- /dev/null +++ b/test/e2e/nullable.ts @@ -0,0 +1,13 @@ +export const input = { + type: 'object', + properties: { + foo: { + type: 'string', + nullable: true + }, + bar: { + type: ['string', 'number'], + nullable: true + } + } +} diff --git a/test/normalizer/nullableAddsNullToType.json b/test/normalizer/nullableAddsNullToType.json new file mode 100644 index 00000000..a232921d --- /dev/null +++ b/test/normalizer/nullableAddsNullToType.json @@ -0,0 +1,33 @@ +{ + "name": "Nullable adds null to type", + "in": { + "$id": "a", + "type": "object", + "properties": { + "foo": { + "type": "string", + "nullable": true + }, + "bar": { + "type": ["string", "number"], + "nullable": true + } + }, + "required": [], + "additionalProperties": false + }, + "out": { + "$id": "a", + "type": "object", + "properties": { + "foo": { + "type": ["string", "null"] + }, + "bar": { + "type": ["string", "number", "null"] + } + }, + "required": [], + "additionalProperties": false + } +}