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;
      }


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
  • etc.
  • etc.
  • etc.
Was this page helpful?