“Promise<ConnectionPool> & void”类型缺少“ConnectionPool”类型的以下属性

亚历克斯·塞拉菲尼

我正在尝试使用 mssql 包建立连接并返回池。

const sqlConfig = {
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_CATALOG,
    server: process.env.SERVER_HOST
}

export async function connect(){
    try{
        const pool = await sql.connect(sqlConfig)
        return pool
    }catch(err){
        throw err
    }
}

但是,在返回池时,我收到以下 lint 错误:Type 'Promise<ConnectionPool> & void' is missing the following properties from type 'ConnectionPool': connected, connecting, healthy, driver, and 26 more.

我应该如何重写代码以将池返回为 ConnectionPool 而不是 Promise<ConnectionPool> & void?

作为参考,这里是完整的代码:

import sql, { ConnectionPool } from "mssql"
require('dotenv').config()

const sqlConfig = {
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_CATALOG,
    server: process.env.SERVER_HOST
}

export async function connect():Promise<ConnectionPool>{
    try{
        const pool = await sql.connect(sqlConfig)
        return pool
    }catch(err){
        throw err
    }
}

我尝试将变量转换为 ConnectionPool 并明确写入预期的返回值,如下所示:

export async function connect():Promise<ConnectionPool>{
    try{
        const pool = await sql.connect(sqlConfig)
        return pool as ConnectionPool
    }catch(err){
        throw err
    }
}

尽管是较旧的帖子,但我还尝试向从https://github.com/tediousjs/node-mssql/issues/1063获取的 @types/mssql 包添加重载。

德里克·劳伦斯

您正在等待承诺将返回值视为 ConnectionPool 对象而不是承诺。

如果您希望连接返回连接池,请将您的返回类型更改为 ConnectionPool,如果您仍然希望它返回一个承诺,请删除如下所示的等待并使用等待调用您的连接函数

export async function connect():Promise<ConnectionPool>{
        return sql.connect(sqlConfig);
    }catch(err){
        throw err
    }
}

然后用await connect()or调用它

connect().then( (pool ) => {
   // Do something with pool here
}

我建议 .then 而不是 await

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

“Promise<ConnectionPool> & void”类型缺少“ConnectionPool”类型的以下属性

类型'Promise <any>'缺少以下属性angular

“Observable<unknown>”类型缺少“Promise<any>”类型中的以下属性

React ts 类型 'Promise<X>' 缺少类型 'X' 中的以下属性

从promise返回值时,出现TS 2739错误。类型“ Promise <any>”缺少类型的以下属性

如何从ConnectionPool获取OObjectDatabaseTx?

正确使用多个ConnectionPool的方法

类型“ {}”缺少类型中的以下属性

错误:“类型'{}'缺少类型的以下属性

类型“ EventTarget”缺少以下属性

类型“BrowserRouter”缺少以下属性... - TypeScript

类型“订阅”缺少以下属性

TS类型缺少以下属性

缺少类型'Observable <PizzaState>的以下属性

在UnboundID LDAP中使用多个线程和Connectionpool

错误pool.ConnectionPool-无法创建池的初始连接

春季:如何确保Tomcat JDBC ConnectionPool可以写入日志

“事件”类型缺少“CronOptions”类型的以下属性

类型“ {}”缺少类型“ IResponseConfig”中的以下属性

类型“{}”缺少类型“RouteComponentProps<{},,>”中的以下属性

类型“ ChildNode”缺少类型“ HTMLOptionElement”中的以下属性

“{}”类型缺少“FooModelDTO”类型中的以下属性

InferableComponentEnhancerWithProps 类型缺少 Component<OwnProps> 类型中的以下属性

“元素”类型缺少“SVGSVGElement”类型中的以下属性

与Typescript反应-类型{}缺少类型的以下属性

类型不匹配?“ ...缺少类型中的以下属性...”

2739 类型缺少类型中的以下属性

类型'Pagination <UserEntity>'缺少类型'UserEntity'中的以下属性:

类型“{}”缺少类型中的以下属性 - TS 错误