Extending types similar to an interface
How would one go about extending types similar to how one would extend an interface in TypeScript? It's really the only thing I feel like is missing for ArkType to be a viable alternative.
A minimal example of what I want for ArkType, but written in TypeScript:
12 Replies
You can do something like this:
If you really need it to work like interfaces, you can do this:
https://discord.com/channels/957797212103016458/1162539860574347385/1162722103959760926
You can chain
.and
or .merge
depending on the behavior you want. Instead of manually typing the keys as never
, you can just add "+": "reject"
on your object definitions to specify that no undeclared keys are allowed.I guess my question is more related to discriminated unions from a DX standpoint. I find myself not being able to declare types as I mostly do in TS with ArkType. And that's the only reason I can't adopt it.
You can literally write:
What could be more similar than that 😅
It is similar, but it's not enforcing a constraint, you could merge with a
kind
not related to the original type.I guess you want
.and
If the types are disjoint for a non-optional key, it would throw a parse error
But the second still wouldn't have to be a subtype of the firstIs there any way to make that work within ArkType?
Or is it planned?
Yeah there are lots of ways one sec
Something like this would be one way, although it would require a full subtype (not missing props):
It would be pretty easy to build a utility function or something that would iterate over each prop and check if it's present instead if you wanted to do that.
Personally I think there would be better ways to express these kinds of relationships in general. I'm not sure I'd add the exact equivalent of
interface extends
to the API when and
and or generics can be used to do something quite similar, but I'm open to considering it more. The implementation would be fairly easy externally anyways, so really a matter of whether it convolutes the APII'm assuming this would break if you had nested discriminated unions
Why?
Another option that would give better type errors if something is incorrect for a complex constraint like that would be something like this:
You could change it to accept a validated definition so you don't have to wrap it in
type
with some extra workI don't think I understand
Could you give an example of nested discriminated unions, similarly to how you would do in TS?
I don't know what you mean you can just do whatever you'd do in TS the same way:
Keep in mind internally arktype always discriminates unions for you so you'll get those optimizations for free without having to do anything special
Including nested discriminated unions