【问题标题】:typecript promise return type asynchronous function打字稿承诺返回类型异步函数
【发布时间】:2021-06-17 00:18:20
【问题描述】:

我有这个异步函数,并试图返回一个对象或 null。

但我在定义类型时出错。

如何定义这种数据类型?

const checkIsValidConnection = async (number: string): Promise<string | null> => {
  const defaultConnection = await GetDefaultConnection();

  const wbot = getWbot(defaultConnection.id);

  const contactId = await wbot.getNumberId(`${number}`);

  return contactId;
};

export default checkIsValidConnection;

键入“联系人 ID | null' 不可分配给类型 'string |空'。
类型“ContactId”不可分配给类型“字符串”。

【问题讨论】:

  • 错误很明显,您正在尝试将显然不是字符串的contactId 分配给字符串返回值。检查wbot.getNumberId 的签名,看看它返回了什么(数字?)。
  • ` export interface ContactId { server: string, user: string, _serialized: string, }` 尝试使用此接口更改字符串。我相信 ContactId 是一个包含这 3 个字段的对象,所以你应该正确声明它
  • contactId的类型是一个对象,但老实说,我尝试使用其他类型,我无法成功。
  • 但是编译器实际上检测到它是WAWEBJS.ContactID github.com/pedroslopez/whatsapp-web.js/blob/master/index.d.ts 这就是TypeScript的美妙之处。
  • @Darkripper 谢谢你的帮助!

标签: typescript


【解决方案1】:

我相信您正在与 https://github.com/pedroslopez/whatsapp-web.js/blob/master/index.d.ts

表示WAWEBJS.ContactID是下面的接口。

interface ContactId { server: string, user: string, _serialized: string}

您应该将您的承诺的返回类型更新为 interface 或坚持使用 WAWEBJS.ContactID

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 2019-04-25
    • 2022-01-26
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多