Skip to content

Commit 8db631b

Browse files
committed
[Fix] Fix detection of annotated props with default value
Fixes #2298
1 parent bbebefd commit 8db631b

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed

lib/util/annotations.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@ function isAnnotatedFunctionPropsDeclaration(node, context) {
1717
return false;
1818
}
1919

20-
const tokens = context.getFirstTokens(node.params[0], 2);
21-
const isAnnotated = node.params[0].typeAnnotation;
22-
const isDestructuredProps = node.params[0].type === 'ObjectPattern';
20+
const typeNode = node.params[0].type === 'AssignmentPattern' ? node.params[0].left : node.params[0];
21+
22+
const tokens = context.getFirstTokens(typeNode, 2);
23+
const isAnnotated = typeNode.typeAnnotation;
24+
const isDestructuredProps = typeNode.type === 'ObjectPattern';
2325
const isProps = tokens[0].value === 'props' || (tokens[1] && tokens[1].value === 'props');
2426

2527
return (isAnnotated && (isDestructuredProps || isProps));

lib/util/propTypes.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ module.exports = function propTypesInstructions(context, components, utils) {
200200
* @returns {ASTNode} The resolved type annotation for the node.
201201
*/
202202
function resolveTypeAnnotation(node) {
203-
let annotation = node.typeAnnotation || node;
203+
let annotation = (node.left && node.left.typeAnnotation) || node.typeAnnotation || node;
204204
while (annotation && (annotation.type === 'TypeAnnotation' || annotation.type === 'NullableTypeAnnotation')) {
205205
annotation = annotation.typeAnnotation;
206206
}

tests/lib/rules/prop-types.js

+29
Original file line numberDiff line numberDiff line change
@@ -2336,6 +2336,19 @@ ruleTester.run('prop-types', rule, {
23362336
foo: PropTypes.number,
23372337
}
23382338
`
2339+
},
2340+
{
2341+
// issue #2298
2342+
code: `
2343+
type Props = {|
2344+
firstname?: string
2345+
|};
2346+
2347+
function Hello({ firstname = 'John' }: Props = {}) {
2348+
return <div>Hello {firstname}</div>
2349+
}
2350+
`,
2351+
parser: parsers.BABEL_ESLINT
23392352
}
23402353
],
23412354

@@ -4621,6 +4634,22 @@ ruleTester.run('prop-types', rule, {
46214634
errors: [{
46224635
message: '\'initialValues\' is missing in props validation'
46234636
}]
4637+
},
4638+
{
4639+
// issue #2298
4640+
code: `
4641+
type Props = {|
4642+
firstname?: string
4643+
|};
4644+
4645+
function Hello({ firstname = 'John', lastname = 'Doe' }: Props = {}) {
4646+
return <div>Hello {firstname} {lastname}</div>
4647+
}
4648+
`,
4649+
parser: parsers.BABEL_ESLINT,
4650+
errors: [{
4651+
message: '\'lastname\' is missing in props validation'
4652+
}]
46244653
}
46254654
]
46264655
});

0 commit comments

Comments
 (0)