Dynamic type based on another value
Given a theoretical example like this:
Is it possible to only have
clauses
be required if agree
is true
?13 Replies
Or of a type with "true"
And a type with false
AAAHHHH
Narrowing 🫠
Thank you!
Not even that. Just use a discriminated union, like you would with raw TS.
Thank you 🙏🙏🙏
Is there an alternative approach to this available via arktype at all? I have run into a similar scenario but with many possible key/value combinations.
Rather than writing a specific type for each scenario and
or
ing them, can I configure a property to be required/optional based on the value(s) of other properties?Can you provide an example? (with 5+ types)
Sure, 2 secs
I think you've got to do effectively the same thing
There might be some logic with scopes you can use, but not certain
Do you need that in types or in runtime only?
Runtime (I think - its used to validate incoming request bodies)
Although thinking about it, I would also like to use it as a Type in the application, so I'm guessing I'll have to do the
or
ingOkay it's a hard question
Yeah if you want it inferred in TS you probably have to do something similar to what you'd do in TS (you can use
key?: never
explicitly if you want for keys to help TS discriminate).
Otherwise I'd say for something like this if you didn't care about having a narrowed type or already had one defined, you could always just write a .narrow
function with arbitrary logic.
This is so overly convoluted compared to (acc, t) => acc.or(t)
for creating a union
That is if you really need to avoid chaining in the first place
Which you definitely don't in a case like thisAs always, thank you for the help 🙏