mvkdiegnhoiw
mvkdiegnhoiw

Reputation: 162

Why is the Bitwise OR operator being used in a variable declaration?

I'm learning Angular and reading through the documentation but I'm confused why the bitwise OR operator is being used in the product variable declaration below. What does the product: Product | undefined line mean?

export class ProductDetailsComponent implements OnInit {

  product: Product | undefined;
  /* ... */
}

Upvotes: 2

Views: 359

Answers (1)

Stefan
Stefan

Reputation: 14863

In that context it is not the OR operator but a "Union Type".

In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc).

A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe ('|') symbol between the types.

Source: https://howtodoinjava.com/typescript/union-types/

So this means that product must be of type Product or undefined. (the undefined part is only relevant if you have strictNullChecks enabled).

Another way to write this is

product?: Product;

Where the question mark indicates that it is an optional parameter.

Upvotes: 5

Related Questions