diff --git a/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts b/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts index 8b7345e82401..4523715d1fbd 100644 --- a/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts +++ b/packages/eslint-plugin/src/rules/non-nullable-type-assertion-style.ts @@ -114,11 +114,21 @@ export default util.createRule({ } if (sameTypeWithoutNullish(assertedTypes, originalTypes)) { + const expressionSourceCode = sourceCode.getText(node.expression); + + const higherPrecedenceThanUnary = + util.getOperatorPrecedence( + services.esTreeNodeToTSNodeMap.get(node.expression).kind, + ts.SyntaxKind.Unknown, + ) > util.OperatorPrecedence.Unary; + context.report({ fix(fixer) { return fixer.replaceText( node, - `${sourceCode.getText(node.expression)}!`, + higherPrecedenceThanUnary + ? `${expressionSourceCode}!` + : `(${expressionSourceCode})!`, ); }, messageId: 'preferNonNullAssertion', diff --git a/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts b/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts index 8b86634d2797..a5dd34cb94aa 100644 --- a/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts +++ b/packages/eslint-plugin/tests/rules/non-nullable-type-assertion-style.test.ts @@ -199,6 +199,48 @@ declare const x: T; const y = x!; `, }, + { + code: ` +declare function nullablePromise(): Promise; + +async function fn(): Promise { + return (await nullablePromise()) as string; +} + `, + errors: [ + { + column: 10, + line: 5, + messageId: 'preferNonNullAssertion', + }, + ], + output: ` +declare function nullablePromise(): Promise; + +async function fn(): Promise { + return (await nullablePromise())!; +} + `, + }, + { + code: ` +declare const a: string | null; + +const b = (a || undefined) as string; + `, + errors: [ + { + column: 11, + line: 4, + messageId: 'preferNonNullAssertion', + }, + ], + output: ` +declare const a: string | null; + +const b = (a || undefined)!; + `, + }, ], });