ARTICLE AD BOX
I am writing a back end in TypeScript using Express and PostgreSQL. I use the pg npm package to connect to the PostgreSQL database and execute a query.
I want to perform some mapping and conversion on the response I get from the database. First, I want to type the response that I get from the query in order to avoid TypeScript warnings about properties that I know will always be in the response.
This is my code:
import { Pool } from 'pg'; const pool = new Pool({ // Config }); const result = await pool.query('SELECT * FROM my_table;') if (result.rows.length > 0 && result.rows[0]) { console.log(result.rows[0].id); }I know that result.rows will be an array of objects, and each object has an id property. However, working with this property results in TypeScript warnings like Unsafe member access .id on an 'any' value.
result has type QueryResult<any>. I tried to create a new array-of-objects type and to use that for result.rows[0], but I got TypeScript warnings about unsafe type assertion.
The documentation says nothing about TypeScript types, and all the examples I could find were with JavaScript. There is also no documentation for the @types/pg module. This seems like a common problem with an obvious solution, but I cannot find it anywhere.
I also found a similar question about MySQL instead of PostgreSQL, but the answer didn’t help, as it’s specific to MySQL.
