I have some TypeScript code that generates typed SQL queries using a schema produced by pg-to-ts:
const getUserByEmail = selectBy('user', ['email']);
// const getUserByEmail: (db: Queryable, select: Pick<User, "email">) => Promise<User[]>
This function works fine and has the correct type. But I don't like how it's displayed. Rather than showing select: Pick<User, "email">
in the parameters list, I'd like it to show select: {email: string}
, which I find much clearer.
What's odd is that writing out Pick<User, "email">
in a type alias produces exactly the desired display when you mouse over it:
type ByEmail = Pick<User, 'email'>;
// type ByEmail = { email: string; }
So how can I match that display in my selectBy
function? Here's a sketch of the implementation (full source is on the TypeScript playground):
export function selectBy<T extends TableNames, K extends keyof TableType<T>>(
tableName: T,
columns: K[],
) {
type OutType = TableType<T>;
type SelectType = Pick<OutType, K>;
let query = `SELECT * FROM ${tableName} ...`;
return async (db: Queryable, select: SelectType): Promise<OutType[]> =>
(
await db.query(
query,
columns.map(c => select[c]),
)
).rows;
}
I'm aware of some of the tricks for controlling type display such as {} &
and Exclude<K, never>
, but I haven't been able to get them to work on this snippet.