gpt4 book ai didi

node.js - TypeScript 编译 node-postgres 的问题

转载 作者:行者123 更新时间:2023-12-03 12:14:13 25 4
gpt4 key购买 nike

免责声明,我对 TypeScript 还很陌生,所以这可能是一个愚蠢的问题!

我正在尝试对我的 Express/Postgres 应用程序使用与 node-postgres docs 中所述相同的设置。 ,我有一个连接到 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);
})
})()

但是,如果我移动 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),
}

并将其导入到主 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);
})
})()

我收到几个投诉:
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.

我意识到这很可能是因为我没有将任何类型添加到 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;

关于node.js - TypeScript 编译 node-postgres 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com