Skip to content

Commit d12fc01

Browse files
authored
prefer-type-error: Ignore error type check (#2729)
1 parent caa1f8b commit d12fc01

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

rules/prefer-type-error.js

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,19 @@ const isTypecheckingMemberExpression = (node, callExpression) => {
7373
return false;
7474
};
7575

76+
const errorNameRegexp = /^(?:[A-Z][\da-z]*)*Error$/;
77+
const isErrorConstructor = node => {
78+
if (node.type === 'Identifier') {
79+
return errorNameRegexp.test(node.name);
80+
}
81+
82+
if (node.type === 'MemberExpression' && !node.optional && !node.computed && node.property.type === 'Identifier') {
83+
return errorNameRegexp.test(node.property.name);
84+
}
85+
86+
return false;
87+
};
88+
7689
const isTypecheckingExpression = (node, callExpression) => {
7790
switch (node.type) {
7891
case 'Identifier': {
@@ -95,11 +108,14 @@ const isTypecheckingExpression = (node, callExpression) => {
95108
}
96109

97110
case 'BinaryExpression': {
98-
return (
99-
node.operator === 'instanceof'
100-
|| isTypecheckingExpression(node.left, callExpression)
101-
|| isTypecheckingExpression(node.right, callExpression)
102-
);
111+
const {operator, left, right} = node;
112+
113+
if (operator === 'instanceof') {
114+
return !isErrorConstructor(right);
115+
}
116+
117+
return isTypecheckingExpression(left, callExpression)
118+
|| isTypecheckingExpression(right, callExpression);
103119
}
104120

105121
case 'LogicalExpression': {

test/prefer-type-error.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,11 @@ test({
276276
throw new Error('Unknown');
277277
}
278278
`,
279+
// Ignore error type check
280+
'if (foo instanceof Error) throw new Error("message")',
281+
'if (foo instanceof CustomError) throw new Error("message")',
282+
'if (foo instanceof lib.Error) throw new Error("message")',
283+
'if (foo instanceof lib.CustomError) throw new Error("message")',
279284
],
280285
invalid: [
281286
{

0 commit comments

Comments
 (0)