Type inference in with predefined types #408
-
Hello! I am wanting to get type inference with my own types I have already defined. Using the example on the readme as a reference: import { email, minLength, object, type Output, parse, string } from 'valibot'; // 1.2 kB
// Create login schema with email and password
const LoginSchema = object({
email: string([email()]),
password: string([minLength(8)]),
});
// Infer output TypeScript type of login schema
type LoginData = Output<typeof LoginSchema>; // { email: string; password: string }
// Returns data as { email: string; password: string }
parse(LoginSchema, { email: '[email protected]', password: '12345678' }); I clearly now have the type type MyLoginType = {email: string, password: string} I want to know if I could do something along the lines of (this is just pseudo-code idea): const LoginSchema = object< MyLoginType >({
email: string([email()]),
password: string([minLength(8)]),
}); Then I could get the following: const loginData = parse(LoginSchema, SomeObject); And this would result in Taking it a step further, it could help with the definition of my schema like I mentioned before like so: const LoginSchema = object< MyLoginType >({
email: string([email()]),
password: number(), // <------------Some TypeScript error here
}); Is anything like this currently possible? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Thank you for creating this discussion. I would write it like this: import * as v from 'valibot';
type LoginData = {
email: string;
password: string;
};
const LoginSchema = v.object({
email: v.string([v.email()]),
password: v.string([v.minLength(8)]),
}) satisfies v.BaseSchema<LoginData>; |
Beta Was this translation helpful? Give feedback.
-
Thank you! |
Beta Was this translation helpful? Give feedback.
Thank you for creating this discussion. I would write it like this: