/
index.js
87 lines (78 loc) · 2.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import isSimpleType from './isSimpleType';
import needWrap from './needWrap';
const schema = [
{
enum: ['verbose', 'shorthand'],
type: 'string',
},
];
const inlineType = (type) => {
const inlined = type.replace(/\s+/g, ' ');
if (inlined.length <= 50) {
return inlined;
} else {
return 'Type';
}
};
export default (defaultConfig, simpleType) => {
const create = (context) => {
const verbose = (context.options[0] || defaultConfig) === 'verbose';
return {
// shorthand
ArrayTypeAnnotation (node) {
const rawElementType = context.getSourceCode().getText(node.elementType);
const inlinedType = inlineType(rawElementType);
const wrappedInlinedType = needWrap(node.elementType) ? '(' + inlinedType + ')' : inlinedType;
if (isSimpleType(node.elementType) === simpleType && verbose) {
context.report({
data: {
type: inlinedType,
wrappedType: wrappedInlinedType,
},
fix (fixer) {
return fixer.replaceText(node, 'Array<' + rawElementType + '>');
},
message: 'Use "Array<{{ type }}>", not "{{ wrappedType }}[]"',
node,
});
}
},
// verbose
GenericTypeAnnotation (node) {
// Don't report on un-parameterized Array annotations. There are valid cases for this,
// but regardless, we must NOT crash when encountering them.
if (node.id.name === 'Array' &&
node.typeParameters && node.typeParameters.params.length === 1) {
const elementTypeNode = node.typeParameters.params[0];
const rawElementType = context.getSourceCode().getText(elementTypeNode);
const inlinedType = inlineType(rawElementType);
const wrappedInlinedType = needWrap(elementTypeNode) ? '(' + inlinedType + ')' : inlinedType;
if (isSimpleType(elementTypeNode) === simpleType && !verbose) {
context.report({
data: {
type: inlinedType,
wrappedType: wrappedInlinedType,
},
fix (fixer) {
if (needWrap(elementTypeNode)) {
return fixer.replaceText(node, '(' + rawElementType + ')[]');
} else {
return fixer.replaceText(node, rawElementType + '[]');
}
},
message: 'Use "{{ wrappedType }}[]", not "Array<{{ type }}>"',
node,
});
}
}
},
};
};
return {
create,
meta: {
fixable: 'code',
},
schema,
};
};