6
votes

I have the Component and I use TypeScript Interface to define its props:

interface Props {
    headerType: DROPDOWN_MENU_TYPE, //DROPDOWN_MENU_TYPE is enum
    headerContent: SVGClass
    isReverse: boolean;
};

const MyComp: React.FunctionComponent<Props> = () => {};

Then I use PropTypes to validate its props in runtime:

DropDownMenu.propTypes = {
    headerType: PropTypes.oneOf(DROPDOWN_MENU_TYPE), //error here
    headerContent: PropTypes.instanceOf(SVGClass),
    isReverse: PropTypes.bool
};

And I got this error:

Argument of type 'typeof DROPDOWN_MENU_TYPE' is not assignable to parameter of type 'readonly DROPDOWN_MENU_TYPE[]'.

Type 'typeof DROPDOWN_MENU_TYPE' is missing the following properties from type 'readonly DROPDOWN_MENU_TYPE[]': length, concat, join, slice, and 16 more.

How can I use TypeScript enum with PropTypes? And how can I solve this error?

2

2 Answers

2
votes

You can try

const DropdownMenuType = PropTypes.oneOf(
  Object.values(DROPDOWN_MENU_TYPE) as DROPDOWN_MENU_TYPE[]
);

DropDownMenu.propTypes = {
  headerType: DropdownMenuType,
  ...
};

Works for me whenever I need to validate against enums.

0
votes

If your enum has numeric values and you want to pass such values, try

headerType: PropTypes.oneOf(
  Object.values(DROPDOWN_MENU_TYPE).filter(x => typeof x === 'number')
)