JustTheSyme
JustTheSyme
DTDrizzle Team
Created by JustTheSyme on 1/5/2024 in #help
How to type a function with column key of table
I can't get this to type correctly. I want field to be a column of table, but typescript keeps saying Type 'Field' cannot be used to index type 'TTable'. What's the best way to do this?
type GetColumnKeys<TTable extends Table> = keyof {
[K in keyof TTable as K extends keyof TTable['_']['columns'] ? K : never]: true
}

async function getOptions<
TTable extends Table,
Field extends GetColumnKeys<TTable>
>(table: TTable, field: Field) {
const column = table[field]
const result = await drizzleDb
.selectDistinct({
option: column
})
.from(table)
.orderBy(column)
return result.map((i) => String(i.option))
}
type GetColumnKeys<TTable extends Table> = keyof {
[K in keyof TTable as K extends keyof TTable['_']['columns'] ? K : never]: true
}

async function getOptions<
TTable extends Table,
Field extends GetColumnKeys<TTable>
>(table: TTable, field: Field) {
const column = table[field]
const result = await drizzleDb
.selectDistinct({
option: column
})
.from(table)
.orderBy(column)
return result.map((i) => String(i.option))
}
6 replies