Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use TypeScript Enum with PropTypes to define React Component props

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?

like image 330
Trí Phan Avatar asked Jun 19 '19 15:06

Trí Phan


People also ask

How do you use PropTypes in a functional component React?

But before using it we will have to import it as always in our app: import PropTypes from 'prop-types'; They are often used after the component ends and starts with the name of the component as shown: import React from 'react'; import { PropTypes } from "prop-types"; const Count = (props) => { return ( <> .........

Does TypeScript have PropTypes?

Props are required in TypeScript In the prop-types package, all props are optional by default. To make a prop required, you will have to use .

Can TypeScript replace PropTypes?

In case of a functional component, it won't be different than how you define default values for parameters in any other normal function. Example: const NavBarMenu = ({ text, active = false }: Props) => { ... } Also TypeScript is not a full replacement for PropTypes, in most cases TS will be sufficient (and better).

Can we use PropTypes in functional component?

In this example, we are using a class component, but the same functionality could also be applied to function components, or components created by React.memo or React.forwardRef . PropTypes exports a range of validators that can be used to make sure the data you receive is valid.


1 Answers

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.

like image 147
Tomas B Avatar answered Sep 27 '22 02:09

Tomas B