简体   繁体   中英

What does it mean by the extra pipeline in the type declaration in typescript

Recently I've declared a type like-

interface SomeType {
  property: {
    a: number;
    b: string;
  } | undefined;
}

But when I saved the type, the vscode (maybe prettier) converts it into-

interface SomeType {
  property:
    | {
        a: number;
        b: string;
      }
    | undefined;
}

So, you see there is an extra | symbol after the property key. So what exactly is it? Can anyone describe the behavior?

Note: This only happens if I set property: {a: number; b: string;} | undefined; property: {a: number; b: string;} | undefined; . If the | undefined | undefined is not set then everything is same as it is.

The behavior is exactly the same as if there was no leading | . It's simply a style choice. It allows, for example

let foo:
  | 'a'
  | 'b'
  | 'c';

whereas if the syntax did not permit the leading | , it'd have to look like

let foo:
    'a'
  | 'b'
  | 'c';

which might grind some people's gears.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM