How to write schemas for this kind of generic type #839
-
how to write schemas from these types? type Condition =
| {
type: 'composite'
operator: 'and' | 'or'
conditions: Condition[]
}
| {
type: 'name'
match: Match<string>
}
| {
type: 'timestamp'
match: Match<number>
}
type GeneralMatch<T> = {
type: 'exact' | 'contains'
value: T
}
type NotMatch<T> = {
type: 'not'
match: GeneralMatch<T>
}
type Match<T extends string | number> = GeneralMatch<T> | NotMatch<T> my try: const GeneralMatch = v.object({
type: v.union([v.literal('exact'), v.literal('contains')]),
value: v.any(), // not sure how to type this for the generic type T
})
const NotMatch = v.object({
type: v.literal('not'),
match: GeneralMatch,
})
const Match = v.union([GeneralMatch, NotMatch])
const Condition: v.GenericSchema<Condition> = v.variant('type', [
v.object({
type: v.literal('composite'),
operator: v.union([v.literal('and'), v.literal('or')]),
conditions: v.lazy(() => v.array(Condition)),
}),
v.object({
type: v.literal('name'),
match: Match,
}),
v.object({
type: v.literal('timestamp'),
match: Match,
}),
]) |
Beta Was this translation helpful? Give feedback.
Answered by
fabian-hiller
Sep 20, 2024
Replies: 1 comment
-
The generic import * as v from 'valibot';
type GenericType<T extends string | number> = { foo: T };
type SpecificType = GenericType<string>;
function genericSchema<
T extends v.StringSchema<undefined> | v.NumberSchema<undefined>,
>(schema: T): v.ObjectSchema<{ foo: T }, undefined> {
return v.object({ foo: schema });
}
const specificSchema = genericSchema(v.string()); Tip: You can replace |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
mattp0123
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The generic
T
ofMatch
basically allows you to decide later to passstring | number
or a more specific type that extends this declaration. The same can be done at runtime using a function. The function simply takes a schema as an argument and dynamically returns a schema that can be used for validation. Here is an example:Tip: Y…