ESlint错误,类型'()=> Promise <void>'从类型'Promise <void>'中缺少以下属性:然后,最后捕获[Symbol.toStringTag]

时间:2020-09-29 07:24:06

标签: javascript typescript eslint typescript-eslint

我遇到一个错误,只能通过添加any作为返回值来解决。

export const dbConnections: any = {};

export const connectDb: Promise<void> = async () => {
    if (dbConnections.isConnected) {
        return;
    }

    try {
        const db = await mongoose.connect(config.get('mongoURI'), {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true,
        });

        dbConnections.isConnected = db.connections[0].readyState;
    } catch (err) {
        createError('Error caught connecting to db!', err);
    }
};

这会引发错误,

export const connectDb: Promise<void> = async () => {
                                        ^^^^^^^^^^^^^
Type '() => Promise<void>' is missing the following properties
  from type 'Promise<void>': then, catch, [Symbol.toStringTag], finally

如果我使用any而不是Promise<void>,则错误消失了,但这显然不是我要解决的方法。如何解决此皮棉错误?

2 个答案:

答案 0 :(得分:0)

问题在函数声明中。您需要将返回类型指定为Promise<void>

export const connectDb = async (): Promise<void> => {
    if (dbConnections.isConnected) {
        return;
    }

    try {
        const db = await mongoose.connect(config.get('mongoURI'), {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true,
        });

        dbConnections.isConnected = db.connections[0].readyState;
    } catch (err) {
        createError('Error caught connecting to db!', err);
    }
};

答案 1 :(得分:0)

打字稿中的异步函数是返回承诺值的函数。 您可以这样定义函数类型:

export const dbConnections: any = {};

export const connectDb: () => Promise<void> = async () => {
    ...
};