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'
如何使用条件参数类型?
解决方案
您应该添加一个类型保护以定义正确的使用类型。你可以尝试这样的事情:
export const isContentType(x: TContent | TSubcontent) : x is TContent {
return x && x.contentId
}
然后使用:
contentID: isContentType(content) ? content.contentID : content.subcontentID,
推荐阅读
- amazon-web-services - 将 DF 创建到 tempView 后运行 Spark Glue 作业时出错
- excel - Excel VBA:在继续之前检查访问标志(布尔值)
- elasticsearch - Elasticsear _search,有可能做到吗?
- docker - Dockerfile for Go 项目的两个可运行的共享包
- swift - UITableView 与 UITextField 滚动到它时滞后
- laravel - 获取 _ctx.route 不是函数
- r - 如何计算重复项和输出变量的来源
- spring - 引起:java.lang.IllegalArgumentException:无法找到带有名称标头的 RoutePredicateFactory
- matplotlib - 来自离散数据点的插值热图
- java - 使用命令行编译java文件时找不到包(javac -classpath)