Skip to content

Commit

Permalink
Print parens for nullable union/intersection types (benjamn#293)
Browse files Browse the repository at this point in the history
* print parens for nullable union/intersection types

* switched to use FastPath#needsParens instead
  • Loading branch information
keyz authored and benjamn committed Jul 7, 2016
1 parent 1c9725d commit dc79e98
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/fast-path.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions test/printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit dc79e98

Please sign in to comment.