How can define this type with arktype?

I'm relatively new to runtime validation and I'm having some trouble with arktype's syntax. This is the valibot's example that I want to replicate: metadata: v.optional( v.array( v.object({ key: v.string(), value: v.string() }) ), [] ) I can't find a similar example on arktype's docs
6 Replies
ssalbdivad
ssalbdivad3w ago
What part specifically are you struggling with, the array of objects? The best way is usually to split up the type like:
const inner = type({ key: "string", value: "string" });

const outer = type({
"metadata?": inner.array(),
});
const inner = type({ key: "string", value: "string" });

const outer = type({
"metadata?": inner.array(),
});
You can also do the same thing while inlining inner, but usually if you're referring to nested objects its best to give the a name so you can easily reuse them
SexyBeast
SexyBeastOP3w ago
Thanks a lot, that solved my question. Could you point out to the section in the docs where these methods are mentioned?
ssalbdivad
ssalbdivad3w ago
Well there's a bunch of different features features there so it depends. Generally speaking, for any given expression like array, you will see an example with tabs like this. The fluent tab shows how to define the expression using a chained method
No description
SexyBeast
SexyBeastOP3w ago
Thanks a lot for the help! I solved it like this:
No description
No description
ssalbdivad
ssalbdivad3w ago
Looks perfect! If you prefer to specify optionality on the values, you can also chain it like metadata.array().optional()

Did you find this page helpful?