React, Typescipt, Conditional rops

Viewed 45

I have this type:

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

But whenever i try to access options it complains that:

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

What is going on? How to fix it?

2 Answers

You should check if 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
}

You need to also declare options in other input types. Since they are nothing, you can type them as undefined and make it optional:

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

See it in action.

Related