Infer types

Another cool feature that my schemas allow you to do is to infer the input and output type. This makes your work even easier, because you don't have to create the type definition additionally.

Infer input types

The input type of a schema corresponds to the TypeScript type that the incoming data of a schema must match to be valid. To extract this type you use the utility type Input.

You are probably interested in input type only in special cases. I recommend you to use the output type in most cases.

import * as v from 'valibot';

const LoginSchema = v.object({
  email: v.string(),
  password: v.string(),
});

type LoginInput = v.Input<typeof LoginSchema>; // { email: string; password: string }

Infer output types

The output type differs from the input type only if you use optional, nullable or nullish with a default value or transform to transform the input of a schema after validation. The output type corresponds to the output of parse and safeParse. To infer it, you use the utility type Output.

import * as v from 'valibot';
import { hashPassword } from '~/utils';

const LoginSchema = v.transform(
  v.object({
    email: v.string(),
    password: v.transform(v.string(), hashPassword),
  }),
  (input) => {
    return {
      ...input,
      timestamp: new Date().toISOString(),
    };
  }
);

type LoginOutput = v.Output<typeof LoginSchema>; // { email: string; password: string; timestamp: string }

Contributors

Thanks to all the contributors who helped make this page better!

  • GitHub profile picture of fabian-hiller
  • GitHub profile picture of gmaxlev

Partners

Thanks to our partners who support the project ideally and financially.

Sponsors

Thanks to our GitHub sponsors who support the project financially.

  • GitHub profile picture of dailydotdev
  • GitHub profile picture of ivan-mihalic
  • GitHub profile picture of KATT
  • GitHub profile picture of osdiab
  • GitHub profile picture of Thanaen
  • GitHub profile picture of ruiaraujo012
  • GitHub profile picture of hyunbinseo
  • GitHub profile picture of caegdeveloper