|
| 1 | +import _ from 'lodash'; |
| 2 | + |
1 | 3 | const schema = []; |
2 | 4 |
|
| 5 | +// const x = []; |
| 6 | +const isEmptyArrayLiteral = (node) => { |
| 7 | + return _.get(node, 'init.type') === 'ArrayExpression' && _.get(node, 'init.elements.length') === 0; |
| 8 | +}; |
| 9 | + |
| 10 | +// const x = new Array(); const y = Array(); |
| 11 | +const isEmptyArrayInstance = (node) => { |
| 12 | + if (_.get(node, 'init.type') === 'NewExpression' || _.get(node, 'init.type') === 'CallExpression') { |
| 13 | + return _.get(node, 'init.callee.name') === 'Array' && _.get(node, 'init.arguments.length') === 0; |
| 14 | + } else { |
| 15 | + return false; |
| 16 | + } |
| 17 | +}; |
| 18 | + |
| 19 | +const isAnnotationOfEmptyArrayInit = (node) => { |
| 20 | + if (_.has(node, 'parent.parent.parent')) { |
| 21 | + const parent = _.get(node, 'parent.parent.parent'); |
| 22 | + const isVariableDeclaration = _.get(parent, 'type') === 'VariableDeclarator'; |
| 23 | + |
| 24 | + return isVariableDeclaration && (isEmptyArrayLiteral(parent) || isEmptyArrayInstance(parent)); |
| 25 | + } else { |
| 26 | + return false; |
| 27 | + } |
| 28 | +}; |
| 29 | + |
3 | 30 | const create = (context) => { |
4 | 31 | return { |
5 | 32 | ArrayTypeAnnotation (node) { |
6 | | - context.report({ |
7 | | - fix (fixer) { |
8 | | - const rawElementType = context.getSourceCode().getText(node.elementType); |
9 | | - |
10 | | - return fixer.replaceText(node, '$ReadOnlyArray<' + rawElementType + '>'); |
11 | | - }, |
12 | | - message: 'Use "$ReadOnlyArray" instead of array shorthand notation', |
13 | | - node |
14 | | - }); |
| 33 | + if (!isAnnotationOfEmptyArrayInit(node)) { |
| 34 | + context.report({ |
| 35 | + fix (fixer) { |
| 36 | + const rawElementType = context.getSourceCode().getText(node.elementType); |
| 37 | + |
| 38 | + return fixer.replaceText(node, '$ReadOnlyArray<' + rawElementType + '>'); |
| 39 | + }, |
| 40 | + message: 'Use "$ReadOnlyArray" instead of array shorthand notation', |
| 41 | + node |
| 42 | + }); |
| 43 | + } |
15 | 44 | }, |
16 | 45 | GenericTypeAnnotation (node) { |
17 | | - if (node.id.name === 'Array') { |
| 46 | + if (node.id.name === 'Array' && !isAnnotationOfEmptyArrayInit(node)) { |
18 | 47 | context.report({ |
19 | 48 | fix (fixer) { |
20 | 49 | return fixer.replaceText(node.id, '$ReadOnlyArray'); |
|
0 commit comments