TS error when creating a variant (discrimated union) dynamically #569
-
I'm trying to create a variant schema from an existing object but I get a TS error. Here is a minimal example import * as v from 'valibot';
const attributes = {
ORTH: {
validation: v.string(),
description: "The exact text of a token.",
},
IS_ALPHA: {
validation: v.boolean(),
description: "Is the token an alpha character?",
},
} as const;
const AttributeSchema = v.variant(
"key",
// ts error here
Object.entries(attributes).map(([key, { validation }]) =>
v.object({
key: v.literal(key),
value: validation,
})
)
);
const result = v.safeParse(AttributeSchema, { key: "ORTH", value: "21" });
console.log(result); The schema parses fine but I get a TS error in the second argument of
Any TS hero that can help me out here? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem is that I can consider changing the types of |
Beta Was this translation helpful? Give feedback.
The problem is that
variant
currently requires that you specify at least two options (otherwisevariant
makes no sense), but TS is not smart enough to know that the return type ofObject.entries(attributes).map(...)
will have two elements. It is just typed as a generic array of object schemas instead of a tuple.I can consider changing the types of
variant
so that TS does not complain. But this has two drawbacks. The first is that TS will stop complaining if you definevariant
with no or only one option. The second is that it will require us to add additional code that slightly increases the bundle size to return an issue if no option (empty array) is specified.