prettier icon indicating copy to clipboard operation
prettier copied to clipboard

Issue parsing arrow functions in union type when not wrapped in parentheses

Open AaronSherwoodForest opened this issue 8 years ago • 1 comments

Prettier 1.15.3 Playground link

--parser typescript
--print-width 50

Input:

export class MyComponent {
  @Input() public myInput: () => Array<MyObject> | Array<MyObject>;
}

Output:

export class MyComponent {
  @Input() public myInput: () =>
    | Array<MyObject>
    | Array<MyObject>;
}

Expected behavior:

export class MyComponent {
  @Input() public myInput:
    | (() => Array<MyObject>)
    | Array<MyObject>;
}

It seems like there's an issue parsing the first arrow function in the union type, because this probably isn't a widely used syntax (in order for this syntax to be valid without parentheses, it has to be the first type in the union type). I looked at the generated AST, and it seemed like it was treating the two sides of the union type identically.

The easy workaround is to insert parentheses around the arrow function manually, at which point it's interpreted correctly:

Input:

export class MyComponent {
  @Input() public myInput: (() => Array<MyObject>) | Array<MyObject>;
}

Output:

export class MyComponent {
  @Input() public myInput:
    | (() => Array<MyObject>)
    | Array<MyObject>;
}

AaronSherwoodForest avatar Nov 30 '18 19:11 AaronSherwoodForest

The parser we use (which uses the official TypeScript parser internally) interprets this as we print it. You can check this by enabling the AST checkbox on the playground in the debug section.

j-f1 avatar Nov 30 '18 21:11 j-f1