首页 > 解决方案 > React、Typescipt、条件 rops

问题描述

我有这种类型:

export type InfoItemProps = (
  | { inputType: 'dropdown-menu'; options: string[] }
  | { inputType: 'text' }
  | { inputType: 'date' }
  | { inputType: 'text-aria' }
  | { inputType: 'phone-number' }
) & {
  name: string;
  labelText: string;
  value: string;
  editValue: string;
  editMode: boolean;
  onEditValueChange: (inputName: string, value: string) => void;
};

但是每当我尝试访问选项时,它都会抱怨:

Property 'options' does not exist on type 
'{ inputType: "text"; } & { name: string; labelText: string; value: string;
 editValue: string; editMode: boolean; onEditValueChange: (inputName: string, value: string) => void; }'.

到底是怎么回事?如何解决?

标签: reactjstypescript

解决方案


您应该检查 inputType === 'dropdown-menu' 是否:

export type InfoItemProps = (
  | { inputType: 'dropdown-menu'; options: string[] }
  | { inputType: 'text' }
  | { inputType: 'date' }
  | { inputType: 'text-aria' }
  | { inputType: 'phone-number' }
) & {
  name: string;
  labelText: string;
  value: string;
  editValue: string;
  editMode: boolean;
  onEditValueChange: (inputName: string, value: string) => void;
};

declare var obj: InfoItemProps;

if (obj.inputType === 'dropdown-menu') {
  obj.options // ok
}

推荐阅读