diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts index 61583878bae..141959ca7af 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts @@ -216,10 +216,17 @@ export default util.createRule({ contextualType, ts.TypeFlags.Null, ); - if ( - (typeIncludesUndefined && contextualTypeIncludesUndefined) || - (typeIncludesNull && contextualTypeIncludesNull) - ) { + + // make sure that the parent accepts the same types + // i.e. assigning `string | null | undefined` to `string | undefined` is invalid + const isValidUndefined = typeIncludesUndefined + ? contextualTypeIncludesUndefined + : true; + const isValidNull = typeIncludesNull + ? contextualTypeIncludesNull + : true; + + if (isValidUndefined && isValidNull) { context.report({ node, messageId: 'contextuallyUnnecessary', diff --git a/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts b/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts index 4b4e496253f..73a8619b6a4 100644 --- a/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts +++ b/packages/eslint-plugin/tests/rules/no-unnecessary-type-assertion.test.ts @@ -104,6 +104,17 @@ class Mx { private prop = 1; } `, + // https://github.com/typescript-eslint/typescript-eslint/issues/1199 + ` +function testFunction(_param: string | undefined): void { /* noop */ } +const value = 'test' as string | null | undefined +testFunction(value!) + `, + ` +function testFunction(_param: string | null): void { /* noop */ } +const value = 'test' as string | null | undefined +testFunction(value!) + `, ], invalid: [