Reputation: 14398
I have the following React Functional Component:
import React, { memo } from 'react';
interface Props {
buttonType?: JSX.IntrinsicElements['button']['type'];
text: string;
};
const defaultProps = {
buttonType: 'button',
};
const Button: React.FunctionComponent<Props> = ({
buttonType,
text,
}) => (
<button type={buttonType}>
{text}
</button>
);
Button.defaultProps = defaultProps;
export default memo(Button);
This throws a Typescript error:
Type '{ buttonType: string; }' is not assignable to type 'Partial<Props>'.
This is how I usually write stateless components, and the error here is because I'm assigning defaultProps to the component. The error goes away if I write the defaultProps declaration as:
Button.defaultProps = {
buttonType: 'button',
};
Why do I get the error when assigning defaultProps from a const, but not if I do it all inline? Isn't it the same thing?
Upvotes: 1
Views: 988
Reputation: 6253
You have to specify the type of buttonType
on your defaultProps
object. This is automatically inferred to be JSX.IntrinsicElements['button']['type']
when you use Button.defaultProps
, but when you create a fresh object, it sees it as a string
.
const defaultProps: Partial<Props> = {
buttonType: 'button',
}
Should work
Upvotes: 1