Correct typings for factory table

Hey all, I'm back again with a problem with typings on a factory function for creating tables. I already asked about this months ago but the solution that another user came up with, which was something similar to what I was doing, is not correct and presents some problems. The goal is to make a factory function that creates a table with some default columns, like timestamps, author columns etc... This is the "solution" we found at the time:
const baseTableSchema = {
id: [...],
createdAt: [...],
updatedAt: [...],
createdBy: [...],
updatedBy: [...],
}
export const createTableFactory = <
TTableName extends string,
TColumnsMap extends Record<string, PgColumnBuilderBase>,
>(
name: TTableName,
fields: TColumnsMap,
extraConfig?: (
self: BuildExtraConfigColumns<
TTableName,
TColumnsMap & typeof baseTableSchema,
"pg"
>,
) => PgTableExtraConfig,
) => {
const { id, ...baseColumns } = baseTableSchema;

return pgTable<string, TColumnsMap & typeof baseTableSchema>(
name,
{
id,
...fields,
...baseColumns,
},
extraConfig,
);
};
const baseTableSchema = {
id: [...],
createdAt: [...],
updatedAt: [...],
createdBy: [...],
updatedBy: [...],
}
export const createTableFactory = <
TTableName extends string,
TColumnsMap extends Record<string, PgColumnBuilderBase>,
>(
name: TTableName,
fields: TColumnsMap,
extraConfig?: (
self: BuildExtraConfigColumns<
TTableName,
TColumnsMap & typeof baseTableSchema,
"pg"
>,
) => PgTableExtraConfig,
) => {
const { id, ...baseColumns } = baseTableSchema;

return pgTable<string, TColumnsMap & typeof baseTableSchema>(
name,
{
id,
...fields,
...baseColumns,
},
extraConfig,
);
};
The problem I'm facing is that the with field when querying the db on the tables created using this factory is typed as {} | undefined, so something like this gives me lots of typescript errors
await db.query.testTable.findMany({
with: {
// no autocomplete with the related tables
testTable2: {
orderBy: (table, {desc}) => ... // both table and desc have type any
}
}
})
await db.query.testTable.findMany({
with: {
// no autocomplete with the related tables
testTable2: {
orderBy: (table, {desc}) => ... // both table and desc have type any
}
}
})
Does anyone know how to correct the typings?
1 Reply
icomad
icomadOP4mo ago
For anyone incurring in the same error, the solution was quite easy, you have to explicitly type the return value of the factory function like this:
export const createTableFactory = <...>(...): PgTableWithColumns<{
name: TTableName;
schema: string | undefined;
columns: BuildColumns<TTableName, TColumnsMap, "pg">;
dialect: "pg";
}> => { ... }
export const createTableFactory = <...>(...): PgTableWithColumns<{
name: TTableName;
schema: string | undefined;
columns: BuildColumns<TTableName, TColumnsMap, "pg">;
dialect: "pg";
}> => { ... }
Want results from more Discord servers?
Add your server