【问题标题】:Async function not allowing return type of two promise types in typescript异步函数不允许在打字稿中返回两种承诺类型
【发布时间】:2020-08-10 05:15:30
【问题描述】:

节点 14.7.0,npm 6.14.7,打字稿 3.7.3。

我有一个查询 postgres 数据库的方法,它会根据参数返回它找到的第一行或查询的整个结果。类似这样:

async getRecord(options: {singleRow: boolean}): Promise<QueryResult> | Promise<Record> {
    const result:QueryResult = await postgres.query(...);
    
    if (options && options.singlerow) {
        return result.rows[0];
    }

    return result;
}

但是,我收到以下错误:The return type of an async function or method must be the global Promise&lt;T&gt; type. 当我删除 | Promise&lt;Record&gt; 部分时,我没有收到错误,即使第一个返回(在 if 语句中)返回 Promise&lt;Record&gt;。我应该怎么做才能解决这个问题?

【问题讨论】:

  • 尝试将您的回报包装成 Promise,例如 Promise.resolve(result.rows[0])

标签: node.js typescript async-await


【解决方案1】:

返回Promise&lt;QueryResult | Record&gt;

async 函数需要一个 Promise 来封装它们返回的任何类型,只有一个顶级 Promise-type-generic 包装了返回类型。

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2019-02-13
    • 2017-12-01
    • 2019-04-25
    • 2023-03-16
    • 2020-08-27
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多