Missing `.exclude()` with functionality of `Exclude<>` in TS
See original GitHub issueHey, first of all thanks so much for the package!
As the title suggests I’m searching for a way to replicate the Exclude<Type, ExcludedUnion>
functionality provided by TS (docs) using zod
. I searched for “exclude” in issues and prs, but didn’t find a single mention of this utility type (outside of internals), therefore I’m opening this issue.
My use case involves unions of many smaller action types, e.g.:
type Actions = { type: "added", ... } | { type: "removed", ... } | { type: "changed", ... } | ... ;
(or rather an equivalent const Actions = z.union([ ... ]);
on which I’m using z.infer
)
I need to retroactively exclude only a few specific actions from the main Actions
type.
Using only TS, I can add a discriminator key such as notA: true
to those few actions and then define:
type ActionsOnlyA = Exclude<Actions, Actions & { notA: true }>;
Using zod, I have to add a discriminator such as isA: true
to a lot more actions to then use:
const ActionsOnlyA = Actions.and(z.object({ isA: z.literal(true) }));
(I still favor this over passing additional schemas for ActionsOnlyA
from the definitions up to the root of the project due to the amount of code.)
Maybe I’m also missing an obvious way on how to get this behavior using the existing functionality… Any advice or comment is highly appreciated 😃
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5
Top GitHub Comments
@LucasForster
I’m absolutely fine with leaving it open and keeping the title to be specifically about
Exclude
/exclude
for now. I added a help wanted label and if someone has the bandwidth to add it, they can use this thread to coordinate with you and others who have a need for it. Thanks again for raising the issue and for providing use-case/context.I was just coming over here to post the same thing, and the same goes with
Pick<type, union>
. There’s a lot of cases where I have one big union, but other components only use sub-sets of that main union. All my API types are provided by passing zod schemas and then the class infers the correct return types from them, so I can’t simply use pick/exclude in type parameters anywhere. For the time being I have to duplicate a lot of code to declare a new zod schema for every possible combination, rather than simplymyMainUnion.exclude([z.literal('one'), z.literal('two')])
, or substitute exclude with pick. I’m sure this is not trivial and perhaps why the functionality doesn’t (yet) exist, but it would be super helpful working with unions to reduce duplicate code.