Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
joshuaavalon opened this issue Jun 11, 2024 · 1 comment
Open

Comments

@joshuaavalon
Copy link

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.

@dearlordylord
Copy link

Hey, I worked on reproduction and my own report before finding there's a report already.

My issue seems to be the same. There's an additional issue reproduction I've prepared https://github.com/dearlordylord/typebox-recursion-transform-bug/blob/master/libs%2Ftypebox%2Fsrc%2Flib%2Ftypebox.ts

mport { Type, StaticDecode, Static } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';

const Recursion = Type.Recursive(Self => Type.Object({
  id: Type.String(),
  children: Type.Transform(
    Type.Array(Self)
  ).Decode((v/*inferred as never[];*/) => v).Encode(v => v),
}));

type Recursion = StaticDecode<typeof Recursion>;

const r: {children: never[]} = Value.Decode(Recursion, {
  children: [
    { children: [] },
    { children: [{ children: [] }] },
  ],
});

function test(node: Recursion) {
  const a: never[] = node.children[0];
  // @ts-expect-error
  const b = node.children[0].children[0].id;
}

when it comes to .Transform inside .Recursive, the type seems to be erased to never

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants