Skip to content

Commit 33dd991

Browse files
Merge pull request #544 from bitgopatmcl/handle-spread-in-tuples
fix: handle spread elements in array initializers
2 parents cd4cdf7 + 58e57f1 commit 33dd991

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

packages/openapi-generator/src/codec.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,31 @@ function parseArrayExpression(
188188
if (E.isLeft(valueE)) {
189189
return valueE;
190190
}
191-
result.push(valueE.right);
191+
// swc sometimes sets this to `null` even though it is supposed to be `undefined`
192+
if (element.spread) {
193+
let init = valueE.right;
194+
if (init.type === 'ref') {
195+
const realInitE = findSymbolInitializer(project, source, init.name);
196+
if (E.isLeft(realInitE)) {
197+
return realInitE;
198+
}
199+
const schemaE = parsePlainInitializer(
200+
project,
201+
realInitE.right[0],
202+
realInitE.right[1],
203+
);
204+
if (E.isLeft(schemaE)) {
205+
return schemaE;
206+
}
207+
init = schemaE.right;
208+
}
209+
if (init.type !== 'tuple') {
210+
return E.left('Spread element must be array literal');
211+
}
212+
result.push(...init.schemas);
213+
} else {
214+
result.push(valueE.right);
215+
}
192216
}
193217
return E.right({ type: 'tuple', schemas: result });
194218
}

packages/openapi-generator/test/codec.test.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,44 @@ testCase('union type is parsed', UNION, {
227227
},
228228
});
229229

230+
const UNION_SPREAD = `
231+
import * as t from 'io-ts';
232+
233+
const common = [t.string];
234+
235+
export const FOO = t.union([...common, t.number]);
236+
`;
237+
238+
testCase('union type with spread is parsed', UNION_SPREAD, {
239+
FOO: {
240+
type: 'union',
241+
schemas: [
242+
{ type: 'primitive', value: 'string' },
243+
{ type: 'primitive', value: 'number' },
244+
],
245+
},
246+
common: {
247+
type: 'tuple',
248+
schemas: [{ type: 'primitive', value: 'string' }],
249+
},
250+
});
251+
252+
const UNION_INLINE_SPREAD = `
253+
import * as t from 'io-ts';
254+
255+
export const FOO = t.union([...[t.string], t.number]);
256+
`;
257+
258+
testCase('union type with inline spread is parsed', UNION_INLINE_SPREAD, {
259+
FOO: {
260+
type: 'union',
261+
schemas: [
262+
{ type: 'primitive', value: 'string' },
263+
{ type: 'primitive', value: 'number' },
264+
],
265+
},
266+
});
267+
230268
const INTERSECTION = `
231269
import * as t from 'io-ts';
232270
export const FOO = t.intersection([t.type({ foo: t.number }), t.partial({ bar: t.string })]);

0 commit comments

Comments
 (0)