无法调用可能“未定义”的对象:导入和使用带有包含异步函数作为属性的返回对象的函数

Cannot invoke an object which is possibly 'undefined': Importing and using function with return object containing async functions as properties

提问人:jjunsa 提问时间:10/29/2023 更新时间:10/30/2023 访问量:34

问:

这是我文件中导出的函数:adapter.ts

import type { Adapter } from "@lib/core/adapters";

export default function MyAdapter (): Adapter {
  return {
    async createUser (user: User) {
      ...
    },
    async findUserByEmail (email) {
      ...
    }
  }
}

我正在导入上述内容并尝试在处理程序函数中使用它:route.ts

import MyAdapter from "./adapter";

const adapter = MyAdapter();

export default async function handler(
  req: Request,
  res: Response
) {
  try {
    const profile = await adapter.findUserByEmail("[email protected]");
    ...
  } catch (e) {}
}

当我执行 时,我收到此 TypeScript 错误:tsc

src/app/api/auth/signup/route.ts:22:37 - error TS2722: Cannot invoke an object which is possibly 'undefined'.

22         const profile = await adapter.findUserByEmail("[email protected]");
                                 ~~~~~~~~~~~~~~~~~~~~~~~

我可以通过初始化常量来“修复”这个问题,如下所示:adapter

const adapter = new (MyAdapter as any)();

但这似乎很骇人听闻,我也不明白发生了什么。函数应该是一个类吗?如果不需要,我不想创建新的实例化。MyAdapter

JavaScript 节点.js 打字稿 ecmascript-6 承诺

评论

0赞 T.J. Crowder 10/29/2023
您从什么类型导入?因为这是定义返回值类型的原因,这显然不是 definitely not .你确定你应该使用该类型,而不是仅仅让 TypeScript 进行推断吗?Adapter@lib/core/adaptersMyAdapterfindUserByEmailundefined

答:

0赞 Sandip Jaiswal 10/30/2023 #1

若要解决此问题,请包含一个接口,该接口通知 TypeScript 编译器返回的对象,该对象将包含使用所需的函数。按如下方式修改适配器:

import type { Adapter } from "@lib/core/adapters";

export interface IMyAdapter extends Adapter {
  createUser: (user: User) => any; // replace any with your Return Type
  findUserByEmail: (email: string) => any;
}

export default function MyAdapter (): IMyAdapter {
  return {
    async createUser (user: User) {
      ...
    },
    async findUserByEmail (email) {
      ...
    }
  }
}