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?
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 ( <> .........
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 .
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With