A
arktype3w ago
dibbo

Generate schema on the fly

Hello, I have a dynamic array of form field definitions that I want to generate validator schema from. Something like
const fields = [
{ label: "Field 1", type: "string", isRequired: true },
{ label: "Field 2", type: "string", isRequired: false },
];

const schema = type(
fields.map((f) => {
if (f.type === "string") {
return type(f.isRequired ? "string>0" : "string");
}
// some other type()s
})
);
const fields = [
{ label: "Field 1", type: "string", isRequired: true },
{ label: "Field 2", type: "string", isRequired: false },
];

const schema = type(
fields.map((f) => {
if (f.type === "string") {
return type(f.isRequired ? "string>0" : "string");
}
// some other type()s
})
);
I've given something similar to the above a go, but I'm getting the following error
Argument of type 'Type<string, {}>[]' is not assignable to parameter of type 'readonly []'.
Target allows only 0 element(s) but source may have more.
Argument of type 'Type<string, {}>[]' is not assignable to parameter of type 'readonly []'.
Target allows only 0 element(s) but source may have more.
Is there any way to sort this error out? Thanks.
2 Replies
ssalbdivad
ssalbdivad3w ago
do you need the output schemas to be inferred as literal objects or are you just creating them within a process where you wouldn't have access to literals like that anyways? the simple answer if you don't need the types is to pass something dynamic like this to type.raw instead of type so it doesn't validate the input if you wanted to map a structure like that and preserve the types it would be possible but you'd have to write some type-level logic to do tha mapping manually
dibbo
dibboOP3w ago
type.raw was exactly what I needed - thank you!

Did you find this page helpful?