Home > Blockchain >  vertical bar and null used for in TypeScript
vertical bar and null used for in TypeScript

Time:03-04

Hi I am new to JavaScript and TypeScript

That does this mean here on the code below

what is use for |?

and what is null = null used for?

let element: HTMLElement | null = null;

CodePudding user response:

let element: HTMLElement | null = null;
// Equivalent to
let element: (HTMLElement | null) = null;

| means make a union type, which means the variable can be any of the types listed.

This code means:

  • Create a variable, called element,
  • that can either be of the type HTMLElement OR null (nothing),
  • and set its initial value to null (nothing).

CodePudding user response:

It defines a union type.

The value of element can be either of the type HTMLElement or the type null.

Note that HTMLElement | null is the type and that = null is the assignment. It is not null = null.


You could rewrite this as:

type PossibleHTMLElement = HTMLElement | null;
let element: PossibleHTMLElement = null;

Which might be clearer.

  • Related