Skip to content

Commit 75e599a

Browse files
authored
feat: include tuple names in json schema (#613)
1 parent 2422f97 commit 75e599a

File tree

4 files changed

+36
-2
lines changed

4 files changed

+36
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export type MyTuple = [a: string, b: 123, c?: boolean, ...d: number[]];
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-07/schema#",
3+
"type": "array",
4+
"items": [
5+
{
6+
"title": "a",
7+
"type": "string"
8+
},
9+
{
10+
"title": "b",
11+
"type": "number",
12+
"const": 123
13+
},
14+
{
15+
"title": "c",
16+
"type": "boolean"
17+
}
18+
],
19+
"minItems": 2,
20+
"additionalItems": {
21+
"title": "d",
22+
"type": "number"
23+
}
24+
}

test/schema.test.ts

+1
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ describe("schema", () => {
297297
assertSchema("type-aliases-recursive-anonymous", "MyAlias");
298298
assertSchema("type-aliases-recursive-export", "MyObject");
299299
*/
300+
assertSchema("type-aliases-tuple-with-names", "MyTuple");
300301
assertSchema("type-aliases-tuple-of-variable-length", "MyTuple");
301302
assertSchema("type-aliases-tuple-with-rest-element", "MyTuple");
302303
assertRejection("type-alias-never", "MyNever", {}, {}, /Unsupported type: never/);

typescript-json-schema.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -657,12 +657,20 @@ export class JsonSchemaGenerator {
657657
if (tupleType) {
658658
// tuple
659659
const elemTypes: ts.NodeArray<ts.TypeNode> = (propertyType as any).typeArguments;
660-
const fixedTypes = elemTypes.map((elType) => this.getTypeDefinition(elType as any));
660+
const targetTupleType = (propertyType as ts.TupleTypeReference).target;
661+
662+
const fixedTypes = elemTypes.map((elType, index) => {
663+
const def = this.getTypeDefinition(elType as any);
664+
const label = targetTupleType.labeledElementDeclarations?.[index]?.name?.getFullText().trim();
665+
if (label) {
666+
def.title = label;
667+
}
668+
return def;
669+
});
661670
definition.type = "array";
662671
if (fixedTypes.length > 0) {
663672
definition.items = fixedTypes;
664673
}
665-
const targetTupleType = (propertyType as ts.TupleTypeReference).target;
666674
definition.minItems = targetTupleType.minLength;
667675
if (targetTupleType.hasRestElement) {
668676
definition.additionalItems = fixedTypes[fixedTypes.length - 1];

0 commit comments

Comments
 (0)