Skip to content

Commit 9829dd3

Browse files
authored
fix(eslint-plugin): [nuta] correctly handle null/undefined separation (typescript-eslint#1201)
1 parent d1de3a7 commit 9829dd3

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,17 @@ export default util.createRule<Options, MessageIds>({
216216
contextualType,
217217
ts.TypeFlags.Null,
218218
);
219-
if (
220-
(typeIncludesUndefined && contextualTypeIncludesUndefined) ||
221-
(typeIncludesNull && contextualTypeIncludesNull)
222-
) {
219+
220+
// make sure that the parent accepts the same types
221+
// i.e. assigning `string | null | undefined` to `string | undefined` is invalid
222+
const isValidUndefined = typeIncludesUndefined
223+
? contextualTypeIncludesUndefined
224+
: true;
225+
const isValidNull = typeIncludesNull
226+
? contextualTypeIncludesNull
227+
: true;
228+
229+
if (isValidUndefined && isValidNull) {
223230
context.report({
224231
node,
225232
messageId: 'contextuallyUnnecessary',

packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,17 @@ class Mx {
104104
private prop = 1;
105105
}
106106
`,
107+
// https://github.com/typescript-eslint/typescript-eslint/issues/1199
108+
`
109+
function testFunction(_param: string | undefined): void { /* noop */ }
110+
const value = 'test' as string | null | undefined
111+
testFunction(value!)
112+
`,
113+
`
114+
function testFunction(_param: string | null): void { /* noop */ }
115+
const value = 'test' as string | null | undefined
116+
testFunction(value!)
117+
`,
107118
],
108119

109120
invalid: [

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy