Skip to content

Commit 0d4ccec

Browse files
committed
feat: 对象动态属性布尔值判断
1 parent d2e84d0 commit 0d4ccec

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

src/lib/parse-schema.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,17 @@ export const parseSchema = (
3737
return `${generateComments(schemaObj)}"${key}"${requiredProperties.includes(key) ? '' : '?'}: ${parseSchema(docs, schemaObj)}`;
3838
});
3939

40-
if (typeof parsed.additionalProperties === 'object') {
41-
properties.push(
42-
`[key: string]: ${parseSchema(docs, refToObject(docs, parsed.additionalProperties))}`,
43-
);
40+
let additionalType: string = '';
41+
if (parsed.additionalProperties === true) {
42+
additionalType = `{ [key: string]: unknown; }`;
43+
} else if (typeof parsed.additionalProperties === 'object') {
44+
additionalType = `{ [key: string]: ${parseSchema(docs, refToObject(docs, parsed.additionalProperties))} }`;
45+
}
46+
if (additionalType) {
47+
additionalType = ' & ' + additionalType;
4448
}
4549

46-
return `({ ${properties.join(';')} }${nullable})`;
50+
return `({ ${properties.join(';')} }${additionalType}${nullable})`;
4751
}
4852
default:
4953
return 'unknown';

test/lib/parse-schema.test.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,17 @@ describe('常规', () => {
9191
test('动态对象属性', () => {
9292
expect(
9393
parseSchema(docs, { type: 'object', additionalProperties: { type: 'string' } }),
94-
).toMatchInlineSnapshot(`"({ [key: string]: (string) })"`);
94+
).toMatchInlineSnapshot(`"({ } & { [key: string]: (string) })"`);
95+
96+
expect(
97+
parseSchema(docs, {
98+
type: 'object',
99+
properties: { foo: { type: 'string' }, bar: { type: 'boolean' } },
100+
additionalProperties: { type: 'string' },
101+
}),
102+
).toMatchInlineSnapshot(
103+
`"({ "foo"?: (string);"bar"?: (boolean) } & { [key: string]: (string) })"`,
104+
);
95105

96106
expect(
97107
parseSchema(docs, {
@@ -100,10 +110,23 @@ describe('常规', () => {
100110
type: 'object',
101111
properties: { foo: { type: 'string' }, bar: { type: 'number' } },
102112
},
113+
nullable: true,
103114
}),
104115
).toMatchInlineSnapshot(
105-
`"({ [key: string]: ({ "foo"?: (string);"bar"?: (number) }) })"`,
116+
`"({ } & { [key: string]: ({ "foo"?: (string);"bar"?: (number) }) } | null)"`,
106117
);
118+
119+
expect(
120+
parseSchema(docs, { type: 'object', additionalProperties: true }),
121+
).toMatchInlineSnapshot(`"({ } & { [key: string]: unknown; })"`);
122+
123+
expect(
124+
parseSchema(docs, { type: 'object', additionalProperties: false }),
125+
).toMatchInlineSnapshot(`"({ })"`);
126+
127+
expect(
128+
parseSchema(docs, { type: 'object', additionalProperties: undefined }),
129+
).toMatchInlineSnapshot(`"({ })"`);
107130
});
108131
});
109132

0 commit comments

Comments
 (0)