How can I do conditional types, mapped types, and optional key modifiers (+?)? #1635
Answered
by
JacobWeisenburger
anthonyma94
asked this question in
Q&A
-
I have a simple type like this in TypeScript: type FilterOptionOperators = "and" | "or" | "not"
// DBFilterCompoundOptions and DBFilterColOptions are the results and don't matter
export type DBFilterCompoundOptions = {
[P in FilterOptionOperators]+?: P extends "not"
? DBFilterCompoundOptions | DBFilterColOptions
: (DBFilterCompoundOptions | DBFilterColOptions)[];
}; How can I do this in Zod? |
Beta Was this translation helpful? Give feedback.
Answered by
JacobWeisenburger
Dec 12, 2022
Replies: 2 comments 1 reply
-
I'm not really sure what you are asking. Could you provide some more info about your use case? |
Beta Was this translation helpful? Give feedback.
1 reply
-
This is the best I could do with what you provided. I don't know what type FilterOptionOperators = 'and' | 'or' | 'not'
type DBFilterCompoundOptions = {
[ P in FilterOptionOperators ]+?: P extends 'not' ? DBFilterCompoundOptions : DBFilterCompoundOptions[]
}
const dbFilterCompoundOptionsSchema: z.ZodType<DBFilterCompoundOptions> = z.lazy( () =>
z.object( {
and: z.array( dbFilterCompoundOptionsSchema ),
or: z.array( dbFilterCompoundOptionsSchema ),
not: dbFilterCompoundOptionsSchema,
} ).deepPartial()
)
console.log(
dbFilterCompoundOptionsSchema.safeParse( {
and: [ { and: [] }, { or: [] } ],
or: [ { or: [] }, { and: [] } ],
not: {
and: [ { and: [] }, { or: [] } ],
or: [ { or: [] }, { and: [] } ],
not: {},
},
} ).success
) // true
console.log(
dbFilterCompoundOptionsSchema.safeParse( {
or: {
and: [ { and: [] }, { or: [] } ],
or: [ { or: [] }, { and: [] } ],
not: {},
},
not: [ { and: [] }, { or: [] } ],
} ).success
) // false |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JacobWeisenburger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is the best I could do with what you provided. I don't know what
DBFilterColOptions
is so I wasn't able to include that in this solution. If you can provide that, I can update the solution.