Home > Net >  Type 'Promise<ConnectionPool> & void' is missing the following properties from type
Type 'Promise<ConnectionPool> & void' is missing the following properties from type

Time:03-26

I'm trying to make a connection and returning the pool using the mssql package.

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
    }
}

However when returning the pool, I get the following lint error: Type 'Promise<ConnectionPool> & void' is missing the following properties from type 'ConnectionPool': connected, connecting, healthy, driver, and 26 more.

How should I rewrite the code to return the pool as a ConnectionPool rather than a Promise<ConnectionPool> & void?

For reference, here's the full code:

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
    }
}

I tried casting the variable to ConnectionPool and explicitly writing the expected return value, like this:

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

I have also tried adding overloads to the @types/mssql package taken from https://github.com/tediousjs/node-mssql/issues/1063 despite being an older post.

CodePudding user response:

You are awaiting a promise is treating return value as a ConnectionPool object and not the promise.

if you want connect to return the connection pool change your return type to ConnectionPool, if you still want it to return a promise remove the await as seen below and call your connect function with await

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

then call it with await connect() or

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

I would suggest the .then instead of await

  • Related