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

问题描述 投票:0回答:1

这是我的

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

当我执行

tsc
时,我收到此 TypeScript 错误:

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 node.js typescript ecmascript-6 promise
1个回答
0
投票

为了解决这个问题,请包含一个接口,通知 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) {
      ...
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.