【问题标题】:MYSql connection in TypeScript Error: No overload matches this call?TypeScript 错误中的 MYSql 连接:没有重载匹配此调用?
【发布时间】:2021-12-31 14:05:19
【问题描述】:

我有 MySql2 数据库配置功能

const db = mysql.createConnection({
 host: process.env['SQL_HOST'],
  user: process.env['SQL_USER'],
  password: process.env['SQL_PASSWORD'],
});

我收到此错误:

No overload matches this call.
  Overload 1 of 2, '(connectionUri: string): Connection', gave the following error.
    Argument of type '{ host: string | undefined; user: string | undefined; password: string | undefined; }' is not assignable to parameter of type 'string'.
  Overload 2 of 2, '(config: ConnectionOptions): Connection', gave the following error.
    Argument of type '{ host: string | undefined; user: string | undefined; password: string | undefined; }' is not assignable to parameter of type 'ConnectionOptions' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
      Types of property 'user' are incompatible.
        Type 'string | undefined' is not assignable to type 'string'.
          Type 'undefined' is not assignable to type 'string'.

有人遇到这个错误吗?

【问题讨论】:

    标签: mysql node.js typescript


    【解决方案1】:

    显然,您已将 exactOptionalPropertyTypes 设置为 true,请参阅 explanation,并牢记这一点并看到 process.env 的所有值都为 string | undefined,您需要执行以下操作:

    const db = mysql.createConnection({
     host: process.env['SQL_HOST'] ?? '',
      user: process.env['SQL_USER'] ?? '',
      password: process.env['SQL_PASSWORD'] ?? '',
    })
    

    或者关闭tsconfig.json中的exactOptionalPropertyTypes选项。

    您可以使用此选项here 我添加了ConnectionOptionsprecess.env 的定义

    【讨论】:

      猜你喜欢
      • 2022-12-07
      • 2020-06-29
      • 2020-02-15
      • 2020-11-28
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2023-01-04
      相关资源
      最近更新 更多