Skip to content

Commit 20ca92a

Browse files
committed
fix(code-gen): correctly type anyOf discriminant validators
1 parent e7656f6 commit 20ca92a

1 file changed

Lines changed: 18 additions & 1 deletion

File tree

packages/code-gen/src/validators/javascript.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,20 @@ export function validatorJavascriptAnyOf(file, type, validatorState) {
357357

358358
// Fast track validators with discriminant. This also gives much better error objects.
359359
if (type.validator.discriminant) {
360+
fileBlockStart(file, `if (!isRecord(${valuePath}))`);
361+
362+
fileWrite(
363+
file,
364+
`${errorKey} = {
365+
key: "validator.object",
366+
value: ${valuePath},
367+
foundType: typeof ${valuePath},
368+
};`,
369+
);
370+
371+
fileBlockEnd(file);
372+
fileBlockStart(file, "else");
373+
360374
const matchableValues = [];
361375

362376
for (const subType of type.values) {
@@ -380,7 +394,7 @@ export function validatorJavascriptAnyOf(file, type, validatorState) {
380394

381395
fileBlockStart(
382396
file,
383-
`if (${valuePath}.${type.validator.discriminant} === "${oneOf}")`,
397+
`if (typeof value === "object" && "${type.validator.discriminant}" in ${valuePath} && ${valuePath}.${type.validator.discriminant} === "${oneOf}")`,
384398
);
385399

386400
validatorState.skipFirstNilCheck = true;
@@ -411,6 +425,9 @@ export function validatorJavascriptAnyOf(file, type, validatorState) {
411425
);
412426
fileBlockEnd(file);
413427

428+
// isRecord end
429+
fileBlockEnd(file);
430+
414431
return;
415432
}
416433

0 commit comments

Comments
 (0)