Skip to content

How to write schemas for this kind of generic type #839

Answered by fabian-hiller
mattp0123 asked this question in Q&A
Discussion options

You must be logged in to vote

The generic T of Match basically allows you to decide later to pass string | 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:

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: Y…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by mattp0123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants