Skip to content

Commit 56bdaf7

Browse files
committed
fix: correctly generate anyOf on unions with string and boolean constant
1 parent b3ca204 commit 56bdaf7

File tree

3 files changed

+42
-7
lines changed

3 files changed

+42
-7
lines changed

src/TypeFormatter/LiteralUnionTypeFormatter.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,18 @@ export class LiteralUnionTypeFormatter implements SubTypeFormatter {
5555
appendTypeValues(type, typeValues);
5656
}
5757

58-
const schema = {
59-
type: toEnumType(Array.from(typeNames)),
60-
enum: Array.from(typeValues),
61-
};
62-
63-
return preserveLiterals ? { anyOf: [{ type: "string" }, schema] } : schema;
58+
const schema =
59+
typeNames.size === 1 && typeValues.size === 1
60+
? {
61+
type: toEnumType(Array.from(typeNames)),
62+
const: Array.from(typeValues)[0],
63+
}
64+
: {
65+
type: toEnumType(Array.from(typeNames)),
66+
enum: Array.from(typeValues),
67+
};
68+
69+
return hasString ? { anyOf: [{ type: "string" }, schema] } : schema;
6470
}
6571

6672
public getChildren(): BaseType[] {

test/valid-data/type-union/main.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ type MyType4 = "s" | 1;
66
type MyType5 = "s" | 1[];
77
type MyType6 = ("s" | 1)[];
88

9+
type MyType7 = string | true;
10+
type MyType8 = "s" | true;
11+
912
export interface TypeUnion {
1013
var1: MyType1;
1114
var2: MyType2;
@@ -14,4 +17,7 @@ export interface TypeUnion {
1417
var4: MyType4;
1518
var5: MyType5;
1619
var6: MyType6;
20+
21+
var7: MyType7;
22+
var8: MyType8;
1723
}

test/valid-data/type-union/schema.json

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,27 @@
7070
]
7171
},
7272
"type": "array"
73+
},
74+
"var7": {
75+
"anyOf": [
76+
{
77+
"type": "string"
78+
},
79+
{
80+
"const": true,
81+
"type": "boolean"
82+
}
83+
]
84+
},
85+
"var8": {
86+
"enum": [
87+
"s",
88+
true
89+
],
90+
"type": [
91+
"string",
92+
"boolean"
93+
]
7394
}
7495
},
7596
"required": [
@@ -78,7 +99,9 @@
7899
"var3",
79100
"var4",
80101
"var5",
81-
"var6"
102+
"var6",
103+
"var7",
104+
"var8"
82105
],
83106
"type": "object"
84107
}

0 commit comments

Comments
 (0)