Typescript条件参数类型不起作用



设置一些类型。。

type TContent = {
_id: string;
category_filters: IFilter[] | [];
contentID: string;
contentType: string;
dateCreated: string;
description_html: string;
icon_url: string;
importedContent: boolean;
isBootstrapped: boolean;
langLocale: string;
lastUpdated: string;
level: string | [];
org: null;
products?: IFilter[] | [];
retired: boolean;
roles: IFilter[] | [];
subcontentOrder: [];
success_html: string;
tags: IFilter[] | [];
title: string;
trail_ids: string[];
};
type TSubcontent = {
_id: string;
assessment?: TAssessment;
challengeTime: string;
content: string;
contentType: string;
isBootstrapped: boolean;
langLocale: string;
org: string | null;
retired: boolean;
subcontentID: string | null;
subContentType: string;
tags: IFilter[] | [];
title: string;
};

使用类型。。


function onUpdateTagPoints(points: number): void {
const dispatchArg = filterActions.updateTagPoints({
points: points,
contentID: content.contentID || content.subcontentID,
contentType: content.contentType || content.subContentType,
});
dispatch(dispatchArg);
}
}

失败,返回。。。

Property 'contentID' does not exist on type 'TContent | TSubcontent'.
Property 'contentID' does not exist on type 'TSubcontent'

如何使用条件参数类型?

您应该添加一个typeguard,以便在使用中定义正确的类型。你可以试试这样的东西:

export const isContentType(x: TContent | TSubcontent) : x is TContent {
return x && x.contentId
}

然后使用:

contentID: isContentType(content) ? content.contentID : content.subcontentID,

相关内容

最新更新