New rule: require explicitly typed `defaultProps`
See original GitHub issueIt’s easy write a component with unsafe defaultProps:
interface MyComponentProps {
onClick?: React.MouseEventHandler<HTMLElement>;
}
class MyComponent extends React.Component<MyComponentProps> {
static defaultProps = {
onClick: 42
};
render() {
return <div onClick={this.props.onClick} />;
}
}
So it’s useful to enforce declaring an explicit type for static defaultProps
(which should basically always be Partial<P>
where P
is the type of the component’s props), which would catch such silly mistakes:
interface MyComponentProps {
onClick?: React.MouseEventHandler<HTMLElement>;
}
class MyComponent extends React.Component<MyComponentProps> {
static defaultProps: Partial<MyComponentProps> = {
// ^^^^^^^^^^^^ Type { onClick: number } is not convertible to Partial<MyComponentProps> or some error message along these lines
onClick: 42
};
}
Issue Analytics
- State:
- Created 5 years ago
- Reactions:4
- Comments:5 (3 by maintainers)
Top Results From Across the Web
Eslint: Problem with default props in functional component ...
Eslint react plugin complain with this error ESLint: propType "gretting" is not required, but has no corresponding defaultProps declaration.( ...
Read more >vue/require-default-prop
This rule requires default value to be set for each props that are not marked as required (except Boolean props).
Read more >12 essential ESLint rules for React - LogRocket Blog
This rule enforces that all buttons explicitly have a type attribute — even ones that are intended as Submit buttons. By being explicit, ......
Read more >Should we ever explicitly set default props to undefined?
I'd be concerned about accidentally passing in undefined though? I ended up making a custom prop like so: const orFalse = type =>...
Read more >Typing defaultProps - React TypeScript Cheatsheets
As per this tweet, defaultProps will eventually be deprecated. You can check the discussions here: ... The consensus is to use object default...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
I think it would be useful and would be happy to accept a PR!
Actually, in TypeScript 3.0, you don’t want to explicitly type defaultProps. So, maybe instead of requiring an explicit type, a rule that checks that the inferred type of
defaultProps
is assignable to the class’s props interface would be valuable—which would definitely require the type checker.