【问题标题】:TypeScript compile problems with node-postgresTypeScript 编译 node-postgres 的问题
【发布时间】:2019-12-08 20:57:40
【问题描述】:

预先声明,我对 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.

我意识到这很可能是因为我的 db.ts 文件中的 query 函数中没有添加任何类型,但我实际上也不知道如何正确添加它们以使这一切正常工作!

【问题讨论】:

    标签: node.js typescript node-postgres


    【解决方案1】:

    嗯,这似乎行得通!我只是把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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      相关资源
      最近更新 更多