Skip to content

Commit cb92bd2

Browse files
committed
fix: catch toString and String() usage
1 parent 2b0d70c commit cb92bd2

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

lib/rules/no-array-index-key.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,40 @@ module.exports = {
150150
identifiers.filter(isArrayIndex).forEach(() => {
151151
context.report({node, message: ERROR_MESSAGE});
152152
});
153+
154+
return;
155+
}
156+
157+
if (node.type === 'CallExpression'
158+
&& node.callee
159+
&& node.callee.type === 'MemberExpression'
160+
&& node.callee.object
161+
&& isArrayIndex(node.callee.object)
162+
&& node.callee.property
163+
&& node.callee.property.type === 'Identifier'
164+
&& node.callee.property.name === 'toString'
165+
) {
166+
// key={bar.toString()}
167+
context.report({
168+
node,
169+
message: ERROR_MESSAGE
170+
});
171+
return;
172+
}
173+
174+
if (node.type === 'CallExpression'
175+
&& node.callee
176+
&& node.callee.type === 'Identifier'
177+
&& node.callee.name === 'String'
178+
&& Array.isArray(node.arguments)
179+
&& node.arguments.length > 0
180+
&& isArrayIndex(node.arguments[0])
181+
) {
182+
// key={String(bar)}
183+
context.report({
184+
node: node.arguments[0],
185+
message: ERROR_MESSAGE
186+
});
153187
}
154188
}
155189

tests/lib/rules/no-array-index-key.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,22 @@ ruleTester.run('no-array-index-key', rule, {
7575
code: 'foo.map((baz, i) => <Foo key />)'
7676
},
7777

78+
{
79+
code: 'foo.map((bar, i) => <Foo key={i.baz.toString()} />)'
80+
},
81+
82+
{
83+
code: 'foo.map((bar, i) => <Foo key={i.toString} />)'
84+
},
85+
86+
{
87+
code: 'foo.map((bar, i) => <Foo key={String()} />)'
88+
},
89+
90+
{
91+
code: 'foo.map((bar, i) => <Foo key={String(baz)} />)'
92+
},
93+
7894
{
7995
code: 'foo.reduce((a, b) => a.concat(<Foo key={b.id} />), [])'
8096
},
@@ -119,6 +135,16 @@ ruleTester.run('no-array-index-key', rule, {
119135
errors: [{message: 'Do not use Array index in keys'}]
120136
},
121137

138+
{
139+
code: 'foo.map((bar, i) => <Foo key={i.toString()} />)',
140+
errors: [{message: 'Do not use Array index in keys'}]
141+
},
142+
143+
{
144+
code: 'foo.map((bar, i) => <Foo key={String(i)} />)',
145+
errors: [{message: 'Do not use Array index in keys'}]
146+
},
147+
122148
{
123149
code: 'foo.map((bar, anything) => <Foo key={anything} />)',
124150
errors: [{message: 'Do not use Array index in keys'}]

0 commit comments

Comments
 (0)