Skip to content

Commit

Permalink
feat(schema): support required
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Dec 14, 2022
1 parent ef1a009 commit f75c15c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
19 changes: 16 additions & 3 deletions src/generator/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,13 @@ function _genTypes(
buff.push(...generateJSDoc(val, opts));
if (val.tsType) {
buff.push(
`${escapeKey(key)}${opts.partial ? "?" : ""}: ${val.tsType},\n`
`${escapeKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: ${
val.tsType
},\n`
);
} else if (val.type === "object") {
buff.push(
`${escapeKey(key)}${opts.partial ? "?" : ""}: {`,
`${escapeKey(key)}${isRequired(schema, key, opts) ? "" : "?"}: {`,
..._genTypes(val, spaces, opts),
"},\n"
);
Expand All @@ -130,7 +132,11 @@ function _genTypes(
} else {
type = getTsType(val, opts);
}
buff.push(`${escapeKey(key)}${opts.partial ? "?" : ""}: ${type},\n`);
buff.push(
`${escapeKey(key)}${
isRequired(schema, key, opts) ? "" : "?"
}: ${type},\n`
);
}
}

Expand Down Expand Up @@ -257,3 +263,10 @@ function generateJSDoc(schema: Schema, opts: GenerateTypesOptions): string[] {

return [];
}

function isRequired(schema: Schema, key: string, opts: GenerateTypesOptions) {
if (Array.isArray(schema.required) && schema.required.includes(key)) {
return true;
}
return !opts.partial;
}
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export interface Schema extends TypeDescriptor {
default?: JSValue;
resolve?: ResolveFn;
properties?: { [key: string]: Schema };
required?: string[];
title?: string;
description?: string;
$schema?: string;
Expand Down
10 changes: 9 additions & 1 deletion test/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,16 @@ describe("resolveSchema", () => {
type: "array",
items: {
type: "object",
required: ["foo"],
properties: {
foo: {
type: "number",
description: "This is foo prop",
},
bar: {
type: "number",
description: "This is bar prop",
},
},
},
},
Expand All @@ -98,7 +103,10 @@ describe("resolveSchema", () => {
manual?: Array<{
/** This is foo prop */
foo?: number,
foo: number,
/** This is bar prop */
bar?: number,
}>,
}"
`);
Expand Down

0 comments on commit f75c15c

Please sign in to comment.