Skip to content

Instantly share code, notes, and snippets.

@shiawuen
Last active June 12, 2020 14:59
Show Gist options
  • Save shiawuen/7f607b7acb8b5e76671eadbc0a8ded79 to your computer and use it in GitHub Desktop.
Save shiawuen/7f607b7acb8b5e76671eadbc0a8ded79 to your computer and use it in GitHub Desktop.
Example to extract type from argument with generic types
// Given type definition below
interface IQueryType { params: any, result: any }
class Query<T extends IQueryType> {
run: (params: T['params']) => T['result']
}
// If we need to have our DB acquire connection
// and then release the after query, it can
// then be done in this way
const createDbQuery = (dbPool: Pool) => <P, R> (
query: Query<{ params: P, result: R}>,
params: P
): Promise<R[]> => {
const client = await dbPool.connect()
try {
return await query.run(params)
} finally {
client.release()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment