What's the propose of a leading pipe when declaring a type on Typescript

帅比萌擦擦* 提交于 2021-02-02 09:56:24

问题


Using Prettiefier I noticed that this code block is formated 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?


回答1:


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


来源:https://stackoverflow.com/questions/59302392/whats-the-propose-of-a-leading-pipe-when-declaring-a-type-on-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!