Narrow type based on another property's value
Hey, I've been using ArkType for a few days now - loving it so far. One thing I'd love to be able to do is narrow a type based on the value of another property in the object. eg.
given this code, I would want the type of 'value' to change based on the 'type' property. if 'type ' is 'string', then I'd want value to be narrowed to 'string', but if 'type' is 'Color', I'd want it to be narrowed to 'string.hex'. Is there currently a way to do this in the ArkType system?
Many thanks in advance,
Chris
4 Replies
You may be able to do something with generics, but I'm not sure ArkType's generic definitions support conditionals like this... you could try
Otherwise you can do a top-level narrow. Something like
Potentially with an
else
on the data.type === "Color"
, if you want to disallow hex when type
isn't "Color"
Not that the types probably won't be narrowed though
Maybe you can fix that with .narrow(...).as<NarrowedType>()
if it matters to youwhat you are describing sounds more suited for a discriminated union and wouldn't need all this code
thank you so much for the quick response. the generic approach didn't seem to support he conditionals, but the top level narrow did the trick!
Generic is also possible you just need the hkt one