Skip to content

Commit 388a36c

Browse files
authored
fix(no-unnecessary-assertion): don't report for any and unknown types (#1918)
* fix(no-unnecessary-assertion): don't report for `any` and `unknown `types * test(no-unnecessary-assertion): add a case with `never`
1 parent badfe77 commit 388a36c

2 files changed

Lines changed: 48 additions & 18 deletions

File tree

src/rules/__tests__/no-unnecessary-assertion.test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,18 @@ const generateValidCases = (
8888
8989
expect(add(1, 1)).not.${matcher}();
9090
`,
91+
dedent`
92+
declare function mx(): any;
93+
94+
expect(mx()).${matcher}();
95+
expect(mx()).not.${matcher}();
96+
`,
97+
dedent`
98+
declare function mx(): unknown;
99+
100+
expect(mx()).${matcher}();
101+
expect(mx()).not.${matcher}();
102+
`,
91103
dedent`
92104
declare function mx(): string | ${thing};
93105
@@ -259,6 +271,21 @@ const generateInvalidCases = (
259271
],
260272
},
261273

274+
{
275+
code: dedent`
276+
declare function mx(): never;
277+
278+
expect(mx()).not.${matcher}();
279+
`,
280+
errors: [
281+
{
282+
messageId: 'unnecessaryAssertion',
283+
data: { thing },
284+
line: 3,
285+
},
286+
],
287+
},
288+
262289
{
263290
code: dedent`
264291
const result = "hello world".match("sunshine") ?? [];

src/rules/no-unnecessary-assertion.ts

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -81,29 +81,32 @@ export default createRule<Options, MessageIds>({
8181

8282
const [argument] = jestFnCall.head.node.parent.arguments;
8383

84-
const isTypePossible = canBe(
85-
services.getTypeAtLocation(argument),
84+
let desiredType = TypeFlags.Any | TypeFlags.Unknown;
85+
86+
// add in the appropriate type flag based on the matcher being used
87+
desiredType |=
8688
matcherName === 'toBeNaN'
8789
? TypeFlags.NumberLike
8890
: matcherName === 'toBeNull'
8991
? TypeFlags.Null
90-
: TypeFlags.Undefined,
91-
);
92-
93-
if (!isTypePossible) {
94-
context.report({
95-
messageId: 'unnecessaryAssertion',
96-
data: {
97-
thing:
98-
matcherName === 'toBeNaN'
99-
? 'a number'
100-
: matcherName === 'toBeNull'
101-
? 'null'
102-
: 'undefined',
103-
},
104-
node,
105-
});
92+
: TypeFlags.Undefined;
93+
94+
if (canBe(services.getTypeAtLocation(argument), desiredType)) {
95+
return;
10696
}
97+
98+
context.report({
99+
messageId: 'unnecessaryAssertion',
100+
data: {
101+
thing:
102+
matcherName === 'toBeNaN'
103+
? 'a number'
104+
: matcherName === 'toBeNull'
105+
? 'null'
106+
: 'undefined',
107+
},
108+
node,
109+
});
107110
},
108111
};
109112
},

0 commit comments

Comments
 (0)