fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
5.88k stars 181 forks source link

Force typeing on object schema #571

Closed kenhuang closed 3 months ago

kenhuang commented 4 months ago

In zod we can do this:

type Test {
  field1?: string,
  field2?: string,
}

const TestSchema: z.ZodType<Test> = z.object({
  field1: z.string().optional(),
  field2: z.string().optional(),
});

Is anything similar in valibot? Thanks for the awsome library!

fabian-hiller commented 4 months ago

Yes, please try out BaseSchema:

import * as v from 'valibot';

type Test {
  field1?: string,
  field2?: string,
}

const TestSchema: v.BaseSchema<Test> = v.object({
  field1: v.optional(v.string()),
  field2: v.optional(v.string()),
});
fabian-hiller commented 4 months ago

Hint: Sometimes satisfies is better to not lose type safety for specific object related information:

import * as v from 'valibot';

type Test = {
  field1?: string,
  field2?: string,
}

const TestSchema = v.object({
  field1: v.optional(v.string()),
  field2: v.optional(v.string()),
}) satisfies v.BaseSchema<Test>;
NagRock commented 1 month ago

Hey @fabian-hiller,

Base schema requires 3 generics arguments, so the provided example doesnt work.

fabian-hiller commented 1 month ago

Since we rewrote the whole library with v0.31.0, our implementation changed a bit. Just change BaseSchema to GenericSchema.

import * as v from 'valibot';

type Test = {
  field1?: string,
  field2?: string,
}

const TestSchema = v.object({
  field1: v.optional(v.string()),
  field2: v.optional(v.string()),
}) satisfies v.GenericSchema<Test>;
NagRock commented 1 month ago

Thanks, I will give a try.