14

Using Prettier I noticed that this code block is formatted to contain an extra leading pipe, see the following example:

// before Prettier
let foo: {
    [k: string]: any
} | boolean;

// after Prettier
const actions:
  | {
      [k: string]: any;
    }
  | boolean = true;

Notice the pipe added by Prettier on the type declaration.

This could also be declared in a single line, and prettier keeps the format without adding the extra pipe:

const actions: { [k: string]: any } | boolean = true;

My doubt is why is this pipe added? Does it change anything at the Typescript level?

Koterpillar
  • 7,883
  • 2
  • 25
  • 41
a--m
  • 4,716
  • 1
  • 39
  • 59
  • 1
    It may be to allow for easier addition and deletion of alternations. Also, seeing each `|` on its own indented line followed by the type makes the logic a bit clearer at a glance – CertainPerformance Dec 12 '19 at 10:23
  • 1
    Its just nicer syntax. Very popular in functional languages. Its neutral if there is a `|` as first or not, – Maciej Sikora Dec 12 '19 at 10:31

1 Answers1

25

It's purely stylistic, there is no functional difference.

Consider the following:

type Foo = Bar
  | Baz
  | Bap

compared to this:

type Foo =
  | Bar
  | Baz
  | Bap

The second example is a lot cleaner, and it's immediately clear that the three things on the right side of the |s are the constituents of the union.

Clearly, you wouldn't add a leading | when defining everything on one line:

type T = A | B
bugs
  • 14,631
  • 5
  • 48
  • 52