diff --git a/crates/oxc_formatter/src/parentheses/expression.rs b/crates/oxc_formatter/src/parentheses/expression.rs index c2719d3d52134..c70014eff2623 100644 --- a/crates/oxc_formatter/src/parentheses/expression.rs +++ b/crates/oxc_formatter/src/parentheses/expression.rs @@ -99,10 +99,7 @@ impl<'a> NeedsParentheses<'a> for AstNode<'a, IdentifierReference<'a>> { } name => { // - matches!( - self.parent, - AstNodes::TSSatisfiesExpression(_) | AstNodes::TSAsExpression(_) - ) && matches!( + if !matches!( name, "await" | "interface" @@ -112,6 +109,29 @@ impl<'a> NeedsParentheses<'a> for AstNode<'a, IdentifierReference<'a>> { | "component" | "hook" | "type" + ) { + return false; + } + + let mut parent = self.parent; + while matches!( + parent, + AstNodes::TSSatisfiesExpression(_) | AstNodes::TSAsExpression(_) + ) { + parent = parent.parent(); + } + + // Early return if the parent isn't a `TSSatisfiesExpression` or `TSAsExpression` + if core::ptr::eq(self.parent, parent) { + return false; + } + + matches!( + parent, AstNodes::ExpressionStatement(stmt) if + !matches!( + stmt.parent.parent(), AstNodes::ArrowFunctionExpression(arrow) + if arrow.expression() + ) ) } } diff --git a/crates/oxc_formatter/tests/fixtures/ts/assignments/type.ts b/crates/oxc_formatter/tests/fixtures/ts/assignments/type.ts new file mode 100644 index 0000000000000..50b0963d7617a --- /dev/null +++ b/crates/oxc_formatter/tests/fixtures/ts/assignments/type.ts @@ -0,0 +1,8 @@ +(type) as unknown; +(type) satisfies unknown; + +() => (type) as unknown; +() => (type) satisfies unknown; + +((type) as any)['t']; +((type) satisfies any)['t']; diff --git a/crates/oxc_formatter/tests/fixtures/ts/assignments/type.ts.snap b/crates/oxc_formatter/tests/fixtures/ts/assignments/type.ts.snap new file mode 100644 index 0000000000000..a05d41f046006 --- /dev/null +++ b/crates/oxc_formatter/tests/fixtures/ts/assignments/type.ts.snap @@ -0,0 +1,24 @@ +--- +source: crates/oxc_formatter/tests/fixtures/mod.rs +--- +==================== Input ==================== +(type) as unknown; +(type) satisfies unknown; + +() => (type) as unknown; +() => (type) satisfies unknown; + +((type) as any)['t']; +((type) satisfies any)['t']; + +==================== Output ==================== +(type) as unknown; +(type) satisfies unknown; + +() => type as unknown; +() => type satisfies unknown; + +(type as any)["t"]; +(type satisfies any)["t"]; + +===================== End =====================