K
Kysely4mo ago
Ross

Return type when fields are conditional

Probably more of a TypeScript question than a Kysely question, but how would I type the output of a wrapper function that allows the conditional specification of fields. E.g.
export function selectActivitiesByActivityId(activityIds: number[], fields: Array<keyof ActivityHistoryTable> = []) {
const db = createKysely();
let query = db.selectFrom(ACTIVITIES_TABLE)
if(fields.length){
query = query.select(fields);
} else {
query = query.selectAll();
}
query = query.where('activity_id', 'in', activityIds);
return query.execute();
}
export function selectActivitiesByActivityId(activityIds: number[], fields: Array<keyof ActivityHistoryTable> = []) {
const db = createKysely();
let query = db.selectFrom(ACTIVITIES_TABLE)
if(fields.length){
query = query.select(fields);
} else {
query = query.selectAll();
}
query = query.where('activity_id', 'in', activityIds);
return query.execute();
}
The inferred type is {} and I'd like the return type to include the fields that were specified in the fields property?
Solution:
Conditional selects | Kysely
Sometimes you may want to select some fields based on a runtime condition.
Jump to solution
3 Replies
Ross
RossOP4mo ago
With some help from ChatGPT 4o, I eventually got to this which works:
export function selectActivitiesByActivityId<T extends (keyof ActivityHistoryTable)[]>(
activityIds: number[],
fields?: T
): Promise<Array<Pick<ActivityHistoryTable, T[number]>>> {
const db = createKysely();
let query = db.selectFrom(ACTIVITIES_TABLE);

if (fields && fields.length > 0) {
query = query.select(fields);
} else {
query = query.selectAll();
}
query = query.where('activity_id', 'in', activityIds);
return query.execute() as Promise<Array<Pick<ActivityHistoryTable, T[number]>>>;
}
export function selectActivitiesByActivityId<T extends (keyof ActivityHistoryTable)[]>(
activityIds: number[],
fields?: T
): Promise<Array<Pick<ActivityHistoryTable, T[number]>>> {
const db = createKysely();
let query = db.selectFrom(ACTIVITIES_TABLE);

if (fields && fields.length > 0) {
query = query.select(fields);
} else {
query = query.selectAll();
}
query = query.where('activity_id', 'in', activityIds);
return query.execute() as Promise<Array<Pick<ActivityHistoryTable, T[number]>>>;
}
Solution
koskimas
koskimas4mo ago
Conditional selects | Kysely
Sometimes you may want to select some fields based on a runtime condition.
Ross
RossOP4mo ago
Oh, nice. Thank you
Want results from more Discord servers?
Add your server