This function allows the caller to optionally specify which fields to return from a database query.
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();
}
If I remove the if statement and just use selectAll, the compiler can infer that the return type contains all of the fields from the ACTIVITIES_TABLE .
However, with the if statement, the compiler can’t infer the output and just specifies Promise<{}> as the return type. How do I help the compiler to infer the return type that is either all fields or the fields returned that match those that are passed in?