首页 > 解决方案 > 打字稿条件参数类型不起作用

问题描述

设置一些类型..

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'

如何使用条件参数类型?

标签: typescript

解决方案


您应该添加一个类型保护以定义正确的使用类型。你可以尝试这样的事情:

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

然后使用:

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

推荐阅读