Skip to content

Commit

Permalink
[Fix] Fix detection of annotated props with default value
Browse files Browse the repository at this point in the history
Fixes #2298
  • Loading branch information
yannickcr committed Jun 23, 2019
1 parent bbebefd commit 8db631b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
8 changes: 5 additions & 3 deletions lib/util/annotations.js
Expand Up @@ -17,9 +17,11 @@ function isAnnotatedFunctionPropsDeclaration(node, context) {
return false;
}

const tokens = context.getFirstTokens(node.params[0], 2);
const isAnnotated = node.params[0].typeAnnotation;
const isDestructuredProps = node.params[0].type === 'ObjectPattern';
const typeNode = node.params[0].type === 'AssignmentPattern' ? node.params[0].left : node.params[0];

const tokens = context.getFirstTokens(typeNode, 2);
const isAnnotated = typeNode.typeAnnotation;
const isDestructuredProps = typeNode.type === 'ObjectPattern';
const isProps = tokens[0].value === 'props' || (tokens[1] && tokens[1].value === 'props');

return (isAnnotated && (isDestructuredProps || isProps));
Expand Down
2 changes: 1 addition & 1 deletion lib/util/propTypes.js
Expand Up @@ -200,7 +200,7 @@ module.exports = function propTypesInstructions(context, components, utils) {
* @returns {ASTNode} The resolved type annotation for the node.
*/
function resolveTypeAnnotation(node) {
let annotation = node.typeAnnotation || node;
let annotation = (node.left && node.left.typeAnnotation) || node.typeAnnotation || node;
while (annotation && (annotation.type === 'TypeAnnotation' || annotation.type === 'NullableTypeAnnotation')) {
annotation = annotation.typeAnnotation;
}
Expand Down
29 changes: 29 additions & 0 deletions tests/lib/rules/prop-types.js
Expand Up @@ -2336,6 +2336,19 @@ ruleTester.run('prop-types', rule, {
foo: PropTypes.number,
}
`
},
{
// issue #2298
code: `
type Props = {|
firstname?: string
|};
function Hello({ firstname = 'John' }: Props = {}) {
return <div>Hello {firstname}</div>
}
`,
parser: parsers.BABEL_ESLINT
}
],

Expand Down Expand Up @@ -4621,6 +4634,22 @@ ruleTester.run('prop-types', rule, {
errors: [{
message: '\'initialValues\' is missing in props validation'
}]
},
{
// issue #2298
code: `
type Props = {|
firstname?: string
|};
function Hello({ firstname = 'John', lastname = 'Doe' }: Props = {}) {
return <div>Hello {firstname} {lastname}</div>
}
`,
parser: parsers.BABEL_ESLINT,
errors: [{
message: '\'lastname\' is missing in props validation'
}]
}
]
});

0 comments on commit 8db631b

Please sign in to comment.