Zod table+field descriptor generic schema

I'm building a tRPC procedure for listing rows from a table. I want the user to control the ordering of result by supplying an array of objects with table and the corresponding column name. This works:
z.array(
z.object({
field: z.union([
z
.object({
table: z.literal("scenarists"),
field: createInsertSchema(scenarists).keyof(),
})
.transform(({ table, field }) => tables[table][field]),
z
.object({
table: z.literal("users"),
field: createInsertSchema(users).keyof(),
})
.transform(({ table, field }) => tables[table][field]),
]),
order: z.enum(Object.keys(orders) as [keyof typeof orders]),
}),
)
z.array(
z.object({
field: z.union([
z
.object({
table: z.literal("scenarists"),
field: createInsertSchema(scenarists).keyof(),
})
.transform(({ table, field }) => tables[table][field]),
z
.object({
table: z.literal("users"),
field: createInsertSchema(users).keyof(),
})
.transform(({ table, field }) => tables[table][field]),
]),
order: z.enum(Object.keys(orders) as [keyof typeof orders]),
}),
)
I wanted to create a generic function for constructing the descriptor schema based on provided table:
const createFieldDescriptorSchema = <T extends Table>(table: T) =>
z
.object({
table: z.literal(table._.name as T["_"]["name"]),
field: createInsertSchema(table).keyof(),
})
.transform((descriptor) => table[descriptor.field]);
const createFieldDescriptorSchema = <T extends Table>(table: T) =>
z
.object({
table: z.literal(table._.name as T["_"]["name"]),
field: createInsertSchema(table).keyof(),
})
.transform((descriptor) => table[descriptor.field]);
However, I've stumbled upon the following error:
Type 'addQuestionMarks<baseObjectOutputType<{ table: ZodLiteral<T["_"]["name"]>; field: ZodEnum<CastToStringTuple<UnionToTuple<keyof BuildInsertSchema<T, {}, false>, []>>>; }>, any>["field"] | undefined' cannot be used to index type 'T'.ts(2536)
Type 'addQuestionMarks<baseObjectOutputType<{ table: ZodLiteral<T["_"]["name"]>; field: ZodEnum<CastToStringTuple<UnionToTuple<keyof BuildInsertSchema<T, {}, false>, []>>>; }>, any>["field"] | undefined' cannot be used to index type 'T'.ts(2536)
Which (I think) is related to this. Any help would be greately apprecieated, as I'm really stuck at this...
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server