K
Kysely11mo ago
NestarZ

How to loop an array and based on this create a dynamic CTE but preserve type ?

for (const [references, columns] of referencesArray) {
const newQb = qb.with(`cte_${references}`, (wb) => {
wb = wb.selectFrom(references).distinct().selectAll(references);
for (const column of columns) {
wb = wb.innerJoin(
tableName,
sql.ref(`${tableName}.${column.name}`),
sql.ref(`${column.references}.${column.to}`)
);
}
return wb;
});
qb = newQb as any;
}
for (const [references, columns] of referencesArray) {
const newQb = qb.with(`cte_${references}`, (wb) => {
wb = wb.selectFrom(references).distinct().selectAll(references);
for (const column of columns) {
wb = wb.innerJoin(
tableName,
sql.ref(`${tableName}.${column.name}`),
sql.ref(`${column.references}.${column.to}`)
);
}
return wb;
});
qb = newQb as any;
}
But this is not optimal
Solution:
It's impossible to do this while keeping the types. Not only because of Kysely but also because of typescript. - You can't change the type of a variable in typescript. - You can't turn a string into a string literal. - Even if your strings had string literal types, you couldn't loop over them...
Jump to solution
4 Replies
Solution
koskimas
koskimas11mo ago
It's impossible to do this while keeping the types. Not only because of Kysely but also because of typescript. - You can't change the type of a variable in typescript. - You can't turn a string into a string literal. - Even if your strings had string literal types, you couldn't loop over them - etc. - etc. - etc.
NestarZ
NestarZOP11mo ago
ok!! so I can’t apply a reduce function to a QueryBuilder type ?
koskimas
koskimas11mo ago
You can't change the type of a variable If the type doesn't change, you can reduce it
NestarZ
NestarZOP11mo ago
ok thanks will try!! congratz on your helpful work

Did you find this page helpful?