Skip to content

Commit db747d2

Browse files
committed
fix(inline-arrow): add parens for object expression
1 parent fdf56e1 commit db747d2

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

src/commands/_utils.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,13 @@ export function insideRange(node: Tree.Node, range: [number, number], includeSta
2828
&& (includeEnd ? node.range[1] <= range[1] : node.range[1] < range[1])
2929
)
3030
}
31+
32+
export function unwrapType(node: Tree.Node) {
33+
if (node.type === 'TSAsExpression' // foo as number
34+
|| node.type === 'TSSatisfiesExpression' // foo satisfies T
35+
|| node.type === 'TSNonNullExpression' // foo!
36+
|| node.type === 'TSInstantiationExpression' // foo<string>
37+
|| node.type === 'TSTypeAssertion') // <number>foo
38+
return node.expression
39+
return node
40+
}

src/commands/inline-arrow.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,16 @@ run(
5656
`,
5757
errors: ['command-fix'],
5858
},
59+
{
60+
code: $`
61+
/// inline-arrow
62+
export const foo = () => {
63+
return { a: 'b' } as any
64+
}
65+
`,
66+
output: $`
67+
export const foo = () => ({ a: 'b' } as any)
68+
`,
69+
errors: ['command-fix'],
70+
},
5971
)

src/commands/inline-arrow.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Command, Tree } from '../types'
2+
import { unwrapType } from './_utils'
23

34
export const inlineArrow: Command = {
45
name: 'inline-arrow',
@@ -18,15 +19,20 @@ export const inlineArrow: Command = {
1819
)
1920
return ctx.reportError('Arrow function body must have a single statement')
2021
const statement = statements[0] as Tree.ReturnStatement | undefined
22+
const argument: Tree.Node | null = statement?.argument ? unwrapType(statement.argument) : null
23+
const isObject = (argument?.type === 'ObjectExpression')
2124

2225
ctx.report({
2326
node: arrowFn,
2427
loc: body.loc,
2528
message: 'Inline arrow function',
2629
fix(fixer) {
27-
return fixer.replaceTextRange(body.range, statement && statement.argument
30+
let raw = statement && statement.argument
2831
? ctx.getTextOf(statement.argument)
29-
: 'undefined')
32+
: 'undefined'
33+
if (isObject)
34+
raw = `(${raw})`
35+
return fixer.replaceTextRange(body.range, raw)
3036
},
3137
})
3238
},

0 commit comments

Comments
 (0)