Skip to content

Commit 9829dd3

Browse files
authoredNov 16, 2019
fix(eslint-plugin): [nuta] correctly handle null/undefined separation (#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

+11-4
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

+11
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)
Please sign in to comment.