【问题标题】:ESlint error, Type '() => Promise<void>' is missing the following properties from type 'Promise<void>': then, catch, [Symbol.toStringTag], finallyESlint 错误,类型 '() => Promise<void>' 缺少来自类型 'Promise<void>' 的以下属性:然后,catch,[Symbol.toStringTag],最后
【发布时间】:2021-01-14 18:39:16
【问题描述】:

我遇到了一个错误,我只能通过添加 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&lt;void&gt;,那么错误就会消失,但这显然不是我想要解决的问题。如何解决此 lint 错误?

【问题讨论】:

  • 因为您将 function 分配给 connectDb 而不是承诺。您需要将类型设置为 () =&gt; Promise&lt;void&gt; 或将其更改为执行的函数(可能通过使用 IIFE)。
  • 另外,这不是 lint 错误 - 它是 编译器错误。 TS 通过提醒您 想要拥有connectDb 与您 实际拥有connectDb 不匹配来正确地完成其工作。
  • 将其设置为 export const connectDb = async (): Promise&lt;void&gt; =&gt; { 有效,谢谢。我只想指出,这是一个带有 TS 的现有项目,就在一个小时前,我决定按照this 教程将 ESLint 添加到其中,这就是我开始收到此错误的时候。再次感谢
  • 我在尝试Playground Link中的代码时遇到此错误

标签: javascript typescript eslint typescript-eslint


【解决方案1】:

问题在于函数声明。您需要将返回类型指定为Promise&lt;void&gt;

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

【讨论】:

    【解决方案2】:

    打字稿中的异步函数返回承诺值。

    像这样:

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

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 1970-01-01
      • 2016-12-31
      • 2019-12-24
      • 1970-01-01
      • 2018-12-12
      • 2019-04-11
      • 2021-04-02
      • 2019-02-04
      相关资源
      最近更新 更多