Reputation: 680
I'm new to TypeScript and trying to understand how to convert my React Hooks code to be typed. At the moment, I'm getting the following error:
Property 'openMenu' does not exist on type '{ children?: ReactNode; }'
Property 'toggle' does not exist on type '{ children?: ReactNode; }'
Property 'slidein' does not exist on type '{ children?: ReactNode; }'
This is my code:
const Menu: FunctionComponent = ({ openMenu, toggle, slidein }) => {
return (
<>
<div className={`menu ${toggle}`} onClick={openMenu}>
<div className="bar1"></div>
<div className="bar2"></div>
<div className="bar3"></div>
</div>
<div className={`expand ${slidein}`}>
<ul>
<li>
<Link to="/" onClick={openMenu}>
List
</Link>
</li>
<li>
<Link to="/add-user" onClick={openMenu}>
Add User
</Link>
</li>
<li>Add Climb</li>
</ul>
</div>
</>
);
};
export default Menu;
The props are being sent in from the parent App.js file, which would normally be fine, but TypeScript doesn't seem to like this. I've tried adding a type next to each prop, but that doesn't solve the issue either.
package.json
...
"source-map-loader": "^0.2.4",
"ts-loader": "^6.1.2",
"typescript": "^3.6.3",
...
Upvotes: 0
Views: 206
Reputation: 175
You'll need to explicitly define the prop types within the function signature, like so:
export const Menu =
({ openMenu, toggle, slidein }: {
openMenu: () => void;
toggle: boolean;
slidein: boolean;
}) => {
// rest of your code
}
export default Menu;
Better yet, define the type of the props and pass that type definition into the function:
type PropTypes = {
openMenu: () => void;
toggle: boolean;
slideIn: boolean;
}
And pass that into the function:
const Menu: FunctionComponent<PropTypes> = ({ openMenu, toggle, slideIn
}) => {
...
}
Happy coding! ☺️
Upvotes: 1
Reputation: 74770
FunctionComponent
takes a generic type parameter P
, which stands for your props type used in Menu
component. If you don't specify P
, then {}
type is used as the default. This common object type does not specify any property types, so openMenu
, toggle
and slidein
will then be unknown to the compiler.
You will want to specify Menu
like this:
// this is just an example. Replace it with your concrete props type
type MenuProps = {
openMenu(): void;
toggle: boolean;
slidein: string;
};
const Menu: FunctionComponent<MenuProps> = ({ openMenu, toggle, slidein }) => {...}
Upvotes: 1