Vir*_*olf 5 node.js node-postgres typescript
预先声明,我对 TypeScript 相当陌生,所以这可能是一个愚蠢的问题!
我正在尝试对我的 Express/Postgres 应用程序使用与node-postgres 文档中所述相同的设置中所述相同的设置,其中我有一个连接到 PostgreSQL 服务器的模块,并且包含在我需要访问它的任何地方,但我TypeScript 类型遇到一些问题。
在这个例子中,我简化了一切以完全删除 Express。如果我这样做,一切都会正常,并且 TypeScript 的编译器也很高兴:
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);
})
})()
Run Code Online (Sandbox Code Playgroud)
但是,如果我将这些pg函数移至其自己的单独db.ts模块中:
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),
}
Run Code Online (Sandbox Code Playgroud)
并将其导入到主app.ts文件中:
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);
})
})()
Run Code Online (Sandbox Code Playgroud)
我收到一些投诉:
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.
Run Code Online (Sandbox Code Playgroud)
我意识到这可能是因为我没有向文件query中的函数添加任何类型db.ts,但我实际上也不知道如何正确添加它们以使这一切正常工作!
嗯,这似乎有效!我只是改成直接db.ts导出pool:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4685 次 |
| 最近记录: |