[英]How to consume return from a union type in Typescript
从link-preview-js库中,我们有一个 function getLinkPreview
,它有一个类型定义:
export declare function getLinkPreview(text: string, options?: ILinkPreviewOptions): Promise<{
url: string;
mediaType: string;
contentType: string;
favicons: any[];
} | {
url: string;
title: any;
siteName: any;
description: any;
mediaType: any;
contentType: string;
images: string[];
videos: {
url: any;
secureUrl: any;
type: any;
width: any;
height: any;
}[];
favicons: any[];
}>;
当我尝试在我的应用程序中使用它时,如下所示:
const {images} = await getLinkPreview(payload.link);
它在 IDE 和控制台上都会引发错误:
Property 'images' does not exist on type '{ url: string; mediaType: string; contentType: string; favicons: any[]; } | { url: string; title: any; siteName: any; description: any; mediaType: any; contentType: string; images: string[]; videos: { url: any; secureUrl: any; type: any; width: any; height: any; }[]; favicons: any[]; }'.ts(2339)
我怎样才能解决这个问题?
PS:如果我尝试从定义文件中删除第一个返回类型,它可以解决问题。
在这种情况下,编译错误消息非常有说服力。 它抱怨是因为该代码试图执行object 解构以从不能保证包含该属性的 object 中提取属性images
。
getLinkPreview
的返回类型是union type ,这意味着它返回一个 object ,它将满足至少一个 union 类型的成员。 因此,因为getLinkPreview
有可能返回一个 object,如下所示:
{
url: string;
mediaType: string;
contentType: string;
favicons: any[];
}
TypeScript 抱怨这个 object 没有images
属性。
作为一般解决方案,您可以将getLinkPreview
的结果存储在一个变量中,然后对images
属性进行空值检查。 如果它确实具有独特的属性,那么您可以将其转换为适当的类型(您可能需要进行额外的测试)。
在运行时,代码不知道哪个 object getLinkPreview()
将被解析。 Typescript 不会让混乱发生。
要解决此问题,您需要一个类型保护。
几个选项供您选择:
const linkPreview = await getLinkPreview(payload.link);
if ('images' in linkPreview) {
console.log(linkPreview.images)
}
const linkPreview = await getLinkPreview(payload.link);
if (<SecondObjectInterface>linkPreview.images) {
console.log(linkPreview.images)
}
// OR
if ((linkPreview as SecondObjectInterface).images) {
console.log(linkPreview.images)
}
有关类型保护的更多信息在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.