8

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 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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')
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.