Skip to content

Commit aa98f05

Browse files
committed
fix: type generation for nullable types with anyOf, oneOf etc
1 parent 8123811 commit aa98f05

1 file changed

Lines changed: 47 additions & 3 deletions

File tree

lib/process-schema.ts

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,43 @@ export function schemaToType(
100100
};
101101
}
102102

103+
if (
104+
'allOf' in schemaObject ||
105+
'oneOf' in schemaObject ||
106+
'anyOf' in schemaObject
107+
) {
108+
const schemaItems =
109+
schemaObject.allOf || schemaObject.oneOf || schemaObject.anyOf || [];
110+
111+
const union = 'allOf' in schemaObject;
112+
113+
const types = schemaItems
114+
.map((schema) =>
115+
schemaToType(typesAndInterfaces, parentSchema, propertyName, schema),
116+
)
117+
.map((t) => t.type);
118+
119+
const nullable = 'nullable' in schemaObject && schemaObject.nullable;
120+
121+
if (!nullable && types.length === 1 && types[0]) {
122+
return {
123+
name,
124+
hasQuestionToken,
125+
type: types[0],
126+
};
127+
}
128+
129+
return {
130+
name,
131+
hasQuestionToken,
132+
type: union
133+
? // @ts-expect-error -> bad type in ts-morph (arguably)
134+
Writers.unionType(...types, 'null')
135+
: // @ts-expect-error -> bad type in ts-morph (arguably)
136+
Writers.intersectionType(...types, 'null'),
137+
};
138+
}
139+
103140
if (schemaObject.type === 'object') {
104141
return {
105142
name,
@@ -122,13 +159,20 @@ export function schemaToType(
122159
};
123160
}
124161

162+
const type =
163+
schemaObject.type === 'string' && schemaObject.format?.includes('date')
164+
? 'Date'
165+
: schemaObject.type?.toString() || 'never';
166+
167+
if (type === 'never') {
168+
console.warn('WARNING: unknown type', schemaObject);
169+
}
170+
125171
return {
126172
name,
127173
hasQuestionToken,
128174
type: withNullUnion(
129-
schemaObject.type === 'string' && schemaObject.format?.includes('date')
130-
? 'Date'
131-
: schemaObject.type?.toString() || 'never',
175+
type,
132176
'nullable' in schemaObject && schemaObject.nullable,
133177
),
134178
};

0 commit comments

Comments
 (0)