Disclaimer up-front, I'm fairly new to TypeScript so this may be a dumb question!
I'm attempting to use the same setup for my Express/Postgres application as described in the node-postgres docs, where I have a single module that connects to the PostgreSQL server and is included wherever I need to access it, but I'm having some trouble with TypeScript's types.
For this example I've simplified everything down to entirely remove Express. If I do this everything works and TypeScript's compiler is happy:
import { Pool } from 'pg';
const pool = new Pool({
host: process.env.PG_HOST,
port: parseInt(process.env.PG_PORT),
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
database: process.env.PG_DATABASE,
});
(async function getRows() {
const result = await pool.query('SELECT id, message, created FROM media');
interface dbObject {
id: number,
message: string,
created: Date
}
await result.rows.map((row: dbObject) => {
console.log(row.id);
console.log(row.message);
console.log(row.created);
})
})()
However, if I move the pg
functions into its own separate db.ts
module:
import { Pool } from 'pg';
const pool = new Pool({
host: process.env.PG_HOST,
port: parseInt(process.env.PG_PORT),
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
database: process.env.PG_DATABASE,
});
export = {
query: (text, params) => pool.query(text, params),
}
And import it into the main app.ts
file:
import database from './db';
(async function getRows() {
const result = await database.query('SELECT id, message, created FROM media', []);
interface dbObject {
id: number,
message: string,
created: Date
}
await result.rows.map((row: dbObject) => {
console.log(row.id);
console.log(row.message);
console.log(row.created);
})
})()
I get several complaints:
src/app.ts:11:27 - error TS2345: Argument of type '(row: dbObject) => void' is not assignable to parameter of type '(value: any[], index: number, array: any[][]) => void'.
Types of parameters 'row' and 'value' are incompatible.
Type 'any[]' is missing the following properties from type 'dbObject': id, message, created
11 await result.rows.map((row: dbObject) => {
~~~~~~~~~~~~~~~~~~~~
Found 1 error.
I realise it's likely because I don't have any types added to the query
function in my db.ts
file, but I also don't actually know how to correctly add them to make this all work!
Well, this seems to work! I just changed db.ts
to export pool
directly:
import { Pool } from 'pg';
const pool = new Pool({
host: process.env.PG_HOST,
port: parseInt(process.env.PG_PORT),
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
database: process.env.PG_DATABASE,
});
export = pool;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With