Skip to content

Commit 31e4f33

Browse files
committed
Fix require-default-props type annotations detection with ESLint 3
1 parent 69b1317 commit 31e4f33

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

lib/rules/require-default-props.js

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,9 @@ module.exports = {
4242
const propWrapperFunctions = new Set(context.settings.propWrapperFunctions || []);
4343
const configuration = context.options[0] || {};
4444
const forbidDefaultForRequired = configuration.forbidDefaultForRequired || false;
45+
// Used to track the type annotations in scope.
46+
// Necessary because babel's scopes do not track type annotations.
47+
let stack = null;
4548

4649
/**
4750
* Try to resolve the node passed in to a variable in the current scope. If the node passed in is not
@@ -64,6 +67,22 @@ module.exports = {
6467
return node;
6568
}
6669

70+
/**
71+
* Helper for accessing the current scope in the stack.
72+
* @param {string} key The name of the identifier to access. If omitted, returns the full scope.
73+
* @param {ASTNode} value If provided sets the new value for the identifier.
74+
* @returns {Object|ASTNode} Either the whole scope or the ASTNode associated with the given identifier.
75+
*/
76+
function typeScope(key, value) {
77+
if (arguments.length === 0) {
78+
return stack[stack.length - 1];
79+
} else if (arguments.length === 1) {
80+
return stack[stack.length - 1][key];
81+
}
82+
stack[stack.length - 1][key] = value;
83+
return value;
84+
}
85+
6786
/**
6887
* Tries to find the definition of a GenericTypeAnnotation in the current scope.
6988
* @param {ASTNode} node The node GenericTypeAnnotation node to resolve.
@@ -74,7 +93,7 @@ module.exports = {
7493
return null;
7594
}
7695

77-
return variableUtil.findVariableByName(context, node.id.name);
96+
return variableUtil.findVariableByName(context, node.id.name) || typeScope(node.id.name);
7897
}
7998

8099
function resolveUnionTypeAnnotation(node) {
@@ -563,6 +582,22 @@ module.exports = {
563582
});
564583
},
565584

585+
TypeAlias: function(node) {
586+
typeScope(node.id.name, node.right);
587+
},
588+
589+
Program: function() {
590+
stack = [{}];
591+
},
592+
593+
BlockStatement: function () {
594+
stack.push(Object.create(typeScope()));
595+
},
596+
597+
'BlockStatement:exit': function () {
598+
stack.pop();
599+
},
600+
566601
// e.g.:
567602
// type HelloProps = {
568603
// foo?: string
@@ -588,6 +623,7 @@ module.exports = {
588623
FunctionExpression: handleStatelessComponent,
589624

590625
'Program:exit': function() {
626+
stack = null;
591627
const list = components.list();
592628

593629
for (const component in list) {

0 commit comments

Comments
 (0)