Uncaught Error: A discriminator value for key could not be extracted from all schema options #2747
Answered
by
JacobWeisenburger
TitoSniberb
asked this question in
Q&A
-
Having this code: const portfolioManagedInternalizationData = z
.object({ serviceTypeId: z.number().int() })
.passthrough();
const portfolioAdviceInternalizationData = z
.object({
serviceTypeId: z.number().int(),
adviceTypeId: z.number().int(),
bankingEntityId: z.union([z.number(), z.null()]).nullish(),
})
.passthrough();
const portfolioInternalizationData = z.discriminatedUnion("serviceTypeId", [
portfolioManagedInternalizationData,
portfolioAdviceInternalizationData,
]); Why is it showing this error? |
Beta Was this translation helpful? Give feedback.
Answered by
JacobWeisenburger
Sep 21, 2023
Replies: 1 comment 1 reply
-
Try doing something like this: const portfolioManagedInternalizationData = z.object( {
serviceTypeId: z.literal( 'foo' )
} ).passthrough()
const portfolioAdviceInternalizationData = z.object( {
serviceTypeId: z.enum( [ 'bar', 'baz' ] ),
adviceTypeId: z.number().int(),
bankingEntityId: z.number().nullish(),
} ).passthrough()
const portfolioInternalizationData = z.discriminatedUnion( 'serviceTypeId', [
portfolioManagedInternalizationData,
portfolioAdviceInternalizationData,
] )
console.log(
portfolioInternalizationData.safeParse( {
serviceTypeId: 'foo',
} ).success
) // true
console.log(
portfolioInternalizationData.safeParse( {
serviceTypeId: 'bar',
adviceTypeId: 1,
bankingEntityId: null,
} ).success
) // true
console.log(
portfolioInternalizationData.safeParse( {
serviceTypeId: 'baz',
adviceTypeId: 2,
bankingEntityId: 42,
} ).success
) // true If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏 |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
JacobWeisenburger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
z.discriminatedUnion
requires the use of az.literal
orz.enum
. It doesn't work withz.number
.z.union([z.number(), z.null()]).nullish()
is the same asz.number().nullish()
Try doing something like this: