【问题标题】:React, Typescipt, Conditional ropsReact、Typescript、条件道具
【发布时间】:2021-08-03 22:37:42
【问题描述】:

我有这种类型:

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; }'.

发生了什么事?如何解决?

【问题讨论】:

  • 您只能在条件语句/开关中访问选项,例如const info: InfoItemProps.....if(info.inputType === 'dropdown-menu') { // you can access options here }
  • 请给你看 tsconfig。你的代码对我有用

标签: reactjs typescript


【解决方案1】:

您应该检查 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
}

【讨论】:

    【解决方案2】:

    您还需要在其他输入类型中声明options。由于它们什么都不是,您可以将它们输入为 undefined 并将其设为可选:

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

    看in action。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2021-08-04
      • 2021-10-21
      • 2021-06-29
      • 2020-01-25
      相关资源
      最近更新 更多