Question regarding self referencing types #740
-
First of all greate library! Keep up the great work. I have a question regarding a self reference type. I was wondering how could that be achieved using arktype. For more context here are some examples of it in TS and Zod Typescript: type test = {
a: string;
b: string;
} & (
| { c: number }
| {
c: number;
d: test[];
}
); Zod const test: z.ZodType<test> = z.lazy(() =>
z.intersection(
z.object({
a: z.string(),
b: z.string(),
}),
z.union([
z.object({ c: z.number() }),
z.object({ c: z.number(), d: z.array(test) }),
])
)
); I was testing out some of the helper functions to see if I could make this work similarly but wasn't able to do so. Is something like this possible in arktype? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
This is one of the areas where ArkType really shines! Unlike in Zod, self-referencing types can be inferred without duplicating the definition. As of const types = scope({
test: {
a: "string",
b: "string",
c: "number",
"d?": "test[]"
}
}).compile()
// Correctly infers the cyclic type by default
const { data, problems } = types.test({}) If you wanted all the original intersections and unions, here's an example of how you can represent them explicitly using a scope: const types = scope({
ab: {
a: "string",
b: "string"
},
c: { c: "number" },
cd: { c: "number", d: "test[]" },
cOrCd: "c|cd",
test: "ab&cOrCd"
}).compile()
// Still correctly infers the cyclic type by default, though TS isn't quite as eager to simplify all the operations
const { data, problems } = types.test({}) In the next release, we're adding the const test = type({
a: "string",
b: "string",
c: "number",
"d?": "this[]"
})
// Correctly infers the cyclic type by default
const { data, problems } = test({}) Additionally, unlike Zod, ArkType can validate cyclic data without infinitely recursing! Let me know if you have any questions :-) |
Beta Was this translation helpful? Give feedback.
Ahh, that is probably due to this, which I forgot to test as I only checked on my branch where it has been resolved!
#693
This would also affect the intersection case for cyclic references and will be resolved with the next release. In the meantime, if you run into something like this, you can always cast the type using your existing
test
type like this: