Skip to content

Commit

Permalink
fix(eslint-plugin): [non-nullable-type-assertion-style] consider oper…
Browse files Browse the repository at this point in the history
…ator precedence when fixing (#7289)

* fix(eslint-plugin): [non-nullable-type-assertion-style] consider operator precedence when fixing

* test: split huge test case
  • Loading branch information
auvred committed Aug 10, 2023
1 parent 706aed3 commit bad37a2
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
Expand Up @@ -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',
Expand Down
Expand Up @@ -199,6 +199,48 @@ declare const x: T;
const y = x!;
`,
},
{
code: `
declare function nullablePromise(): Promise<string | null>;
async function fn(): Promise<string> {
return (await nullablePromise()) as string;
}
`,
errors: [
{
column: 10,
line: 5,
messageId: 'preferNonNullAssertion',
},
],
output: `
declare function nullablePromise(): Promise<string | null>;
async function fn(): Promise<string> {
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)!;
`,
},
],
});

Expand Down

0 comments on commit bad37a2

Please sign in to comment.