【发布时间】: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.ContactIDgithub.com/pedroslopez/whatsapp-web.js/blob/master/index.d.ts 这就是TypeScript的美妙之处。 -
@Darkripper 谢谢你的帮助!
标签: typescript