Skip to content

Commit 754b872

Browse files
authored
Fix readonly nullable properties (#1036)
The current logic generates invalid TypeScript code with the `immutableTypes` option for nullable properties which include at least one union (potentially nested): Simple example: type: array nullable: true items: oneOf: - type: number - type: string Generated code before and after this PR: readonly before: readonly ((number | string)[]) | null; // Invalid readonly after: (readonly (number | string)[]) | null; // OK
1 parent 69a245d commit 754b872

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/transform/schema-object.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ export function defaultSchemaObjectTransform(
154154
}
155155
}
156156
itemType = tsArrayOf(itemType);
157-
if (schemaObject.nullable) itemType = tsUnionOf(itemType, "null");
158-
return ctx.immutableTypes || schemaObject.readOnly ? tsReadonly(itemType) : itemType;
157+
itemType = ctx.immutableTypes || schemaObject.readOnly ? tsReadonly(itemType) : itemType;
158+
return schemaObject.nullable ? tsUnionOf(itemType, "null") : itemType;
159159
}
160160
}
161161

test/schema-object.test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,33 @@ describe("Schema Object", () => {
447447
);
448448
});
449449
});
450+
451+
describe("immutableTypes", () => {
452+
test("nullable array of records property", () => {
453+
const schema: SchemaObject = {
454+
type: "object",
455+
properties: {
456+
array: {
457+
type: "array",
458+
nullable: true,
459+
items: {
460+
type: "object",
461+
additionalProperties: true,
462+
},
463+
},
464+
},
465+
};
466+
const generated = transformSchemaObject(schema, {
467+
...options,
468+
ctx: { ...options.ctx, immutableTypes: true },
469+
});
470+
expect(generated).toBe(`{
471+
readonly array?: (readonly ({
472+
[key: string]: unknown | undefined;
473+
})[]) | null;
474+
}`);
475+
});
476+
});
450477
});
451478
});
452479

0 commit comments

Comments
 (0)