sinclairzx81 / typebox

Json Schema Type Builder with Static Type Resolution for TypeScript
Other
4.56k stars 148 forks source link

Type.Recursive does not work with Type.Transform for StaticDecode #895

Open joshuaavalon opened 1 month ago

joshuaavalon commented 1 month ago
import { Type } from "@sinclair/typebox";

import type { StaticDecode, StaticEncode, TSchema } from "@sinclair/typebox";

const schema = Type.Recursive(self => Type.Object({
  a: Type.Number(),
  b: Type.Transform(Type.Union([self, Type.Null(), Type.Undefined()]))
    .Decode(v => v ?? undefined)
    .Encode(v => v)
}));

/**
type A = {
    a: number;
    b: ... | null | undefined;
}
 */
type A = StaticEncode<typeof schema>;

/**
type B = {
    a: number;
    b: undefined;
}
 */
type B = StaticDecode<typeof schema>;

You can see b is resolved to undefined even though it should be B | undefined.