Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [consistent-type-assertions] wrap object return value with parentheses #6885

17 changes: 7 additions & 10 deletions packages/eslint-plugin/src/rules/consistent-type-assertions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,13 @@ export default util.createRule<Options, MessageIds>({
: {},
fix:
messageId === 'as'
? (fixer): TSESLint.RuleFix[] => [
fixer.replaceText(
node,
getTextWithParentheses(node.expression),
),
fixer.insertTextAfter(
node,
` as ${getTextWithParentheses(node.typeAnnotation)}`,
),
]
? util.getWrappingFixer({
sourceCode,
node,
innerNode: [node.expression, node.typeAnnotation],
wrap: (expressionCode, typeAnnotationCode) =>
`${expressionCode} as ${typeAnnotationCode}`,
})
: undefined,
});
}
Expand Down
30 changes: 29 additions & 1 deletion packages/eslint-plugin/src/util/getWrappingFixer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ export function getWrappingFixer(
code = `(${code})`;
}

// check the inner node is used as return body of arrow function
if (isObjectExpressionInOneLineReturn(node, innerNode)) {
armano2 marked this conversation as resolved.
Show resolved Hide resolved
// the code we are editing might break arrow function expressions
// let's wrap our node in parens in case it's gotten mistaken as block statement
code = `(${code})`;
}

return code;
});

Expand Down Expand Up @@ -73,12 +80,15 @@ export function isStrongPrecedenceNode(innerNode: TSESTree.Node): boolean {
return (
innerNode.type === AST_NODE_TYPES.Literal ||
innerNode.type === AST_NODE_TYPES.Identifier ||
innerNode.type === AST_NODE_TYPES.TSTypeReference ||
innerNode.type === AST_NODE_TYPES.TSTypeOperator ||
innerNode.type === AST_NODE_TYPES.ArrayExpression ||
innerNode.type === AST_NODE_TYPES.ObjectExpression ||
innerNode.type === AST_NODE_TYPES.MemberExpression ||
innerNode.type === AST_NODE_TYPES.CallExpression ||
innerNode.type === AST_NODE_TYPES.NewExpression ||
innerNode.type === AST_NODE_TYPES.TaggedTemplateExpression
innerNode.type === AST_NODE_TYPES.TaggedTemplateExpression ||
innerNode.type === AST_NODE_TYPES.TSInstantiationExpression
);
}

Expand Down Expand Up @@ -205,3 +215,21 @@ function isLeftHandSide(node: TSESTree.Node): boolean {

return false;
}

/**
* Checks if a node's parent is arrow function expression and a inner node is object expression
*/
function isObjectExpressionInOneLineReturn(
node: TSESTree.Node,
innerNode: TSESTree.Node,
): boolean {
if (
node.parent?.type === AST_NODE_TYPES.ArrowFunctionExpression &&
node.parent?.body === node &&
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
innerNode.type === AST_NODE_TYPES.ObjectExpression
) {
return true;
}

return false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ const x = <A>!'string';
const x = <A>a + b;
const x = <(A)>a + (b);
const x = <Foo>(new Generic<string>());
const x = (new (<Foo>Generic<string>)());`;
const x = (new (<Foo>Generic<string>)());
const x = () => <Foo>{ bar: 5 };
const x = () => <Foo>({ bar: 5 });
const x = () => <Foo>bar;`;

const ANGLE_BRACKET_TESTS = `${ANGLE_BRACKET_TESTS_EXCEPT_CONST_CASE}
const x = <const>{ key: 'value' };
Expand All @@ -24,12 +27,15 @@ const AS_TESTS_EXCEPT_CONST_CASE = `
const x = new Generic<int>() as Foo;
const x = b as A;
const x = [1] as readonly number[];
const x = ('string') as a | b;
const x = !'string' as A;
const x = a as A + b;
const x = a as (A) + (b);
const x = (new Generic<string>()) as Foo;
const x = (new (Generic<string> as Foo)());`;
const x = 'string' as (a | b);
const x = (!'string') as A;
const x = (a as A) + b;
const x = (a as A) + (b);
const x = new Generic<string>() as Foo;
const x = (new (Generic<string> as Foo)());
const x = () => ({ bar: 5 }) as Foo;
const x = () => ({ bar: 5 }) as Foo;
const x = () => bar as Foo;`;

const AS_TESTS = `${AS_TESTS_EXCEPT_CONST_CASE}
const x = { key: 'value' } as const;
Expand Down Expand Up @@ -198,6 +204,18 @@ ruleTester.run('consistent-type-assertions', rule, {
messageId: 'angle-bracket',
line: 11,
},
{
messageId: 'angle-bracket',
line: 12,
},
{
messageId: 'angle-bracket',
line: 13,
},
{
messageId: 'angle-bracket',
line: 14,
},
],
}),
...batchedSingleLineTests({
Expand Down Expand Up @@ -248,6 +266,18 @@ ruleTester.run('consistent-type-assertions', rule, {
messageId: 'as',
line: 11,
},
{
messageId: 'as',
line: 12,
},
{
messageId: 'as',
line: 13,
},
{
messageId: 'as',
line: 14,
},
],
output: AS_TESTS,
}),
Expand Down Expand Up @@ -295,6 +325,18 @@ ruleTester.run('consistent-type-assertions', rule, {
messageId: 'never',
line: 10,
},
{
messageId: 'never',
line: 11,
},
{
messageId: 'never',
line: 12,
},
{
messageId: 'never',
line: 13,
},
],
}),
...batchedSingleLineTests({
Expand Down Expand Up @@ -341,6 +383,18 @@ ruleTester.run('consistent-type-assertions', rule, {
messageId: 'never',
line: 10,
},
{
messageId: 'never',
line: 11,
},
{
messageId: 'never',
line: 12,
},
{
messageId: 'never',
line: 13,
},
],
}),
...batchedSingleLineTests({
Expand Down
78 changes: 62 additions & 16 deletions packages/eslint-plugin/tests/util/getWrappingFixer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@ import type { TSESTree } from '@typescript-eslint/utils';
import { createRule, getWrappingFixer } from '../../src/util';
import { getFixturesRootDir, RuleTester } from '../RuleTester';

const rule = createRule({
const rootPath = getFixturesRootDir();
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: rootPath,
project: './tsconfig.json',
},
});

const voidEverythingRule = createRule({
name: 'void-everything',
defaultOptions: [],
meta: {
Expand Down Expand Up @@ -45,16 +54,7 @@ const rule = createRule({
},
});

const rootPath = getFixturesRootDir();
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: rootPath,
project: './tsconfig.json',
},
});

ruleTester.run('getWrappingFixer', rule, {
ruleTester.run('getWrappingFixer - voidEverythingRule', voidEverythingRule, {
valid: [],
invalid: [
// should add parens when inner expression might need them
Expand Down Expand Up @@ -183,11 +183,6 @@ ruleTester.run('getWrappingFixer', rule, {
errors: [{ messageId: 'addVoid' }],
output: 'function* fn() { yield void wrapMe }',
},
{
code: '() => wrapMe',
errors: [{ messageId: 'addVoid' }],
output: '() => void wrapMe',
},
{
code: 'if (wrapMe) {}',
errors: [{ messageId: 'addVoid' }],
Expand Down Expand Up @@ -309,3 +304,54 @@ ruleTester.run('getWrappingFixer', rule, {
},
],
});

const removeFunctionRule = createRule({
name: 'remove-function',
defaultOptions: [],
meta: {
type: 'suggestion',
fixable: 'code',
docs: {
description:
'Remove function with first arg remaining in random places for test purposes.',
recommended: false,
},
messages: {
removeFunction: 'Please remove this function',
},
schema: [],
},

create(context) {
const sourceCode = context.getSourceCode();

const report = (node: TSESTree.CallExpression): void => {
context.report({
node,
messageId: 'removeFunction',
fix: getWrappingFixer({
sourceCode,
node,
innerNode: [node.arguments[0]],
wrap: code => code,
}),
});
};

return {
'CallExpression[callee.name="fn"]': report,
};
},
});

ruleTester.run('getWrappingFixer - removeFunctionRule', removeFunctionRule, {
valid: [],
invalid: [
// should add parens when a inner node is a part of return body of node's parent
{
code: '() => fn({ x: "wrapObject" })',
errors: [{ messageId: 'removeFunction' }],
output: '() => ({ x: "wrapObject" })',
},
],
});