fabian-hiller / valibot

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

Typescript: Incompatible Index Signatures #670

Closed ShlokDesai33 closed 2 weeks ago

ShlokDesai33 commented 2 weeks ago

This is the schema I'm trying to create:

const formSchema = v.object(
    purchaseForm.reduce(
        (acc, curr) => ({
            ...acc,
            [curr.id]: getEntrySchema(curr),
        }),
        {} as Record<string, ReturnType<typeof getEntrySchema>>,
    ),
);

Here, the purchase form has field names that I cannot know ahead of time (they are randomly generated ids). However, I know the schema of a field depending on it's type (curr.type). Therefore, getEntrySchema returns a valibot object schema using the type of curr.

Typescript is throwing the following error:

Argument of type 'Record<string, { type: LiteralSchema<"number", undefined>; val: NumberSchema<undefined>; } | { type: LiteralSchema<"checkbox", undefined>; val: SchemaWithPipe<...>; } | ... 4 more ... | { ...; }>' is not assignable to parameter of type 'ObjectEntries'.
  'string' index signatures are incompatible.
    Type '{ type: LiteralSchema<"number", undefined>; val: NumberSchema<undefined>; } | { type: LiteralSchema<"checkbox", undefined>; val: SchemaWithPipe<...>; } | ... 4 more ... | { ...; }' is not assignable to type 'BaseSchema<unknown, unknown, BaseIssue<unknown>>'.
      Type '{ type: LiteralSchema<"number", undefined>; val: NumberSchema<undefined>; }' is missing the following properties from type 'BaseSchema<unknown, unknown, BaseIssue<unknown>>': kind, reference, expects, async, _run

How can I fix this? Any help is greatly appreciated!

fabian-hiller commented 2 weeks ago

Maybe Record<typeof purchaseForm[keyof typeof purchaseForm]['id'], ReturnType<typeof getEntrySchema>> but I need the entire code to be able to debug it. You can also have a look at this function with similar code.