diff --git a/lib/fast-path.js b/lib/fast-path.js index 7311e362..255bd2ac 100644 --- a/lib/fast-path.js +++ b/lib/fast-path.js @@ -192,8 +192,8 @@ FPp.needsParens = function(assumeExpressionContext) { return false; } - // Only expressions need parentheses. - if (!n.Expression.check(node)) { + // Only statements don't need parentheses. + if (n.Statement.check(node)) { return false; } @@ -289,6 +289,10 @@ FPp.needsParens = function(assumeExpressionContext) { return false; } + case "IntersectionTypeAnnotation": + case "UnionTypeAnnotation": + return parent.type === "NullableTypeAnnotation"; + case "Literal": return parent.type === "MemberExpression" && isNumber.check(node.value) diff --git a/test/printer.js b/test/printer.js index e5b5147e..d06399c1 100644 --- a/test/printer.js +++ b/test/printer.js @@ -1454,4 +1454,22 @@ describe("printer", function() { var pretty = printer.printGenerically(ast).code; assert.strictEqual(pretty, code); }); + + it("prints parens for nullable union/intersection types", function() { + var code = "type MyType = ?(string | number);"; + + var ast = b.typeAlias( + b.identifier("MyType"), + null, + b.nullableTypeAnnotation( + b.unionTypeAnnotation( + [b.stringTypeAnnotation(), b.numberTypeAnnotation()] + ) + ) + ); + + var printer = new Printer({}); + var pretty = printer.printGenerically(ast).code; + assert.strictEqual(pretty, code); + }); });