fabian-hiller / valibot

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

bug: `transform` output type inside an object is broken on v0.39 #806

Closed cruzdanilo closed 2 months ago

cruzdanilo commented 2 months ago

in v0.39, the output type of an object field with a transform is not working properly, returning the original type before the transformation. execution works as expected, but the typescript compiler fails. here is a reproduction example:

import { array, nullish, object, parse, pipe, string, transform } from "valibot";

function f({ a }: { a: string[] }) {
  console.log(a);
}

const Schema = object({ a: pipe(nullish(array(string())), transform((x) => x ?? ["default"])) });

const output = parse(Schema, { a: null });

f(output);

execution output:

[ 'default' ]

tsc output:

index.ts:12:3 - error TS2345: Argument of type '{ a?: string[]; }' is not assignable to parameter of type '{ a: string[]; }'.
  Property 'a' is optional in type '{ a?: string[]; }' but required in type '{ a: string[]; }'.

12 f(output);
     ~~~~~~

i pushed this same repro to a git repo: https://github.com/cruzdanilo/repro-valibot-transform you can see this same output in the ci workflow log: https://github.com/cruzdanilo/repro-valibot-transform/actions/runs/10614474287/job/29420466950

fabian-hiller commented 2 months ago

Thank you for creating this issue. I recommend that you change your schema. This will also fix this problem. However, I will investigate this problem and may change the current implementation.

You can try my code in this playground.

import * as v from 'valibot';

const Schema = v.object({
  key: v.nullish(v.array(v.string()), ['default']),
});

type Input = v.InferInput<typeof Schema>;
type Output = v.InferOutput<typeof Schema>;
fabian-hiller commented 2 months ago

I agree. When an optional input is transformed to a non-optional value, the output type should reflect this information. I have improved the implementation and added new type test. Thanks for your feedback!

fabian-hiller commented 2 months ago

v0.40.0 is available 🚀