You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从PostgreSQL连接池获取Client后调用query出现TS2339类型错误

解决TypeScript中pg连接池Client.query的类型错误(TS2339)

问题分析

错误TS2339: Property 'query' does not exist on type 'void'说明TypeScript将pool.connect()返回的client推断为void类型,核心原因是类型定义不匹配或解析异常。

解决方案

1. 校验pg与@types/pg版本兼容性

确保@types/pg和pg本体版本匹配:

  • 查看package.json中的版本号,比如pg为^8.11.0,则@types/pg应对应^8.11.0左右的版本
  • 版本不兼容时,重新安装匹配版本:
npm uninstall pg @types/pg
npm install pg@latest @types/pg@latest

2. 明确导入类型并指定Client类型

修改导入逻辑,直接导入PoolClient类型并给client变量指定类型:

// 连接池配置文件
import { Pool, PoolConfig } from 'pg';

const pool = new Pool({
    user: process.env.USER_NAME,
    host: process.env.HOST_NAME,
    database: process.env.DATABASE,
    password: process.env.PASSWORD,
    port: Number(process.env.DB_PORT) // 注意:port需转为数字,原字符串类型会触发类型警告
} as PoolConfig);

export { pool };
// 调用Client的代码
import { PoolClient } from 'pg';
import { pool } from './你的连接池文件路径';

// 手动指定client类型为PoolClient
const client: PoolClient = await pool.connect();

try {
    const res = await client.query('SELECT …', […]);

    if (!res?.rows[0])
        return null;

    return res.rows[0];
} catch (e) {
    throw e;
} finally {
    client.release();
}

3. 修正tsconfig.json配置

移除files数组中的./node_modules/@types/node/index.d.ts,手动添加该文件会干扰类型自动解析:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "strict": true,
        "sourceMap": true,
        "outDir": "build",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "lib": ["es2017"],
        "allowSyntheticDefaultImports": true,
        "skipLibCheck": true
    },
    "exclude": [
        "node_modules",
        "build"
    ],
    "include": [
        "**/*.ts"
    ]
}

4. 清理缓存重新编译

执行命令清理TypeScript缓存,确保类型定义生效:

rm -rf node_modules/.cache
npx tsc --build --clean
npx tsc

内容的提问来源于stack exchange,提问作者user1790300

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:57:20