What does " | " mean in Typescript?

Asked

Viewed 231 times

12

I have the following code:

export type Teste = Observable<'exemplo' | any>;
  • What the bar means | within the generic argument?
  • Is some kind of comparison any and the string for example?
  • 2

    means or as in most languages

2 answers

10


This is used in something called Union types (united types) also called sum types, as opposed to product types or intersection types (intersected types*) that uses the syntax of &.

It is still an OR, but not in the way it is known, it is not exactly a logical expression, although it can be seen as one. An OR shall not be executed at runtime. It indicates that the generic type parameterized there may be one of the types listed there, so in this case you can use this parameterized object with the type exemplo (without quotation marks) or the type any, either of the two would be accepted. But in this case it makes no sense to any involves all types so involves the exemplo also, could write only:

export type Teste = Observable<any>;

I put in the Github for future reference.

  • 1

    I can use the &?

  • 2

    Yes, it’s possible, it’s called intersection types.

9

A type of union describes a value that can be one of several types. We use the vertical bar (|) to separate each type, so [ number | string | boolean ] is the type of value that can be a number, a string or a boolean.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.