Skip to content

Commit 28a9377

Browse files
authored
Fix required additional properties (#932)
* Fix required additional properties handling * Optimize
1 parent 2a205fc commit 28a9377

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/transform/schema.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,22 @@ export function transformSchemaObjMap(obj: Record<string, any>, options: Transfo
5252
}
5353

5454
/** make sure all required fields exist **/
55-
export function addRequiredProps(properties: Record<string, any>, required: Set<string>): string[] {
55+
export function addRequiredProps(
56+
properties: Record<string, any>,
57+
required: Set<string>,
58+
additionalProperties: any,
59+
options: TransformSchemaObjOptions
60+
): string[] {
5661
const missingRequired = [...required].filter((r: string) => !(r in properties));
5762
if (missingRequired.length == 0) {
5863
return [];
5964
}
6065
let output = "";
66+
67+
const valueType = additionalProperties ? transformSchemaObj(additionalProperties, options) : "unknown";
68+
6169
for (const r of missingRequired) {
62-
output += `${r}: unknown;\n`;
70+
output += `${r}: ${valueType};\n`;
6371
}
6472
return [`{\n${output}}`];
6573
}
@@ -131,7 +139,12 @@ export function transformSchemaObj(node: any, options: TransformSchemaObjOptions
131139
}
132140
case "object": {
133141
const isAnyOfOrOneOfOrAllOf = "anyOf" in node || "oneOf" in node || "allOf" in node;
134-
const missingRequired = addRequiredProps(node.properties || {}, node.required || []);
142+
const missingRequired = addRequiredProps(
143+
node.properties || {},
144+
node.required || [],
145+
node.additionalProperties,
146+
options
147+
);
135148
// if empty object, then return generic map type
136149
if (
137150
!isAnyOfOrOneOfOrAllOf &&

test/core/schema.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,29 @@ abc: unknown;
446446
})`);
447447
});
448448

449+
it("object with missing required field but with additionalProperties", () => {
450+
expect(
451+
transform(
452+
{
453+
type: "object",
454+
required: ["abc", "email"],
455+
properties: {
456+
email: { type: "string" },
457+
},
458+
additionalProperties: {
459+
type: "integer",
460+
},
461+
},
462+
{ ...defaults }
463+
)
464+
).to.equal(`({
465+
"email": string;
466+
467+
}) & ({
468+
abc: number;
469+
}) & ({ [key: string]: number; })`);
470+
});
471+
449472
describe("comments", () => {
450473
it("basic", () => {
451474
expect(

0 commit comments

Comments
 (0)