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

Difference in type & parse result #3920

Open
dinfer opened this issue Dec 20, 2024 · 1 comment
Open

Difference in type & parse result #3920

dinfer opened this issue Dec 20, 2024 · 1 comment

Comments

@dinfer
Copy link

dinfer commented Dec 20, 2024

I want to create a zod instance to describe an object, whose keys should not be "$and" and the value should be a string or a number. This is the simplified code I wrote, It works fine in type check, but the success is false.

    const ZRecord = z
      .record(z.string(), z.union([z.string(), z.number()]))
      .and(z.record(z.enum(["$and"]), z.never()));
    type IRecord = z.infer<typeof ZRecord>;
    const zinvalid: IRecord = { $and: 1 }; // Type 'number' is not assignable to type 'undefined'.ts(2322). this is want I want
    const zvalid: IRecord = { a: 1 };
    console.log(ZRecord.safeParse(zinvalid)); // {success:false}
    console.log(ZRecord.safeParse(zvalid)); // {success:false}

    type TRecord = { [key: string]: number | string } & {
      [key in "$and"]?: never;
    };
    const invalid: TRecord = { $and: 1 }; // Type 'number' is not assignable to type 'undefined'.ts(2322). this is want I want
    const valid: TRecord = { a: 1 };

The final goal is to create a zod instance for valid data like this

    type TFilter =
      | ({ [key: string]: string | number } & {
          [key in "$and" | "$or"]?: never;
        })
      | ({ $and: string[] } | { $or: number[] });
    const tvalid1: TFilter = { a: 1 }; // normal keys is string or number
    const tvalid2: TFilter = { $and: ["key"] }; // the value of special key '$and' is a string array and this is the only key allowed here
    const tvalid3: TFilter = { $or: [1] }; // the value of special key '$or' is number array and this is the only key allowed here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@dinfer and others