Home > database >  Nullish coalescing operator (??) with right hand side 'undefined'
Nullish coalescing operator (??) with right hand side 'undefined'

Time:11-05

Is there ever a need to use Nullish coalescing operator (??) where the right hand is undefined? I feel the obvious answer is "No" since the result should always be undefined, but I wonder if anyone had any interesting usage.

const undefValue = undefined;
const useless = undefValue ?? undefined

CodePudding user response:

null and undefined continue to be sort of an annoying thing in javascript programming. When a type has both, this can help you wrangle that.

So because null and undefined both are considered falsy to the ?? operator, that means error:

const a: string | null | undefined = getSomeValue()
const b: string | undefined = a
// Type 'string | null | undefined' is not assignable to type 'string | undefined'.
//  Type 'null' is not assignable to type 'string | undefined'.(2322)

Playground

Could be fixed like this:

const b: string | undefined = a ?? undefined // works

Playground

Or vice versa with:

const b: string | null = a ?? null // works

Another way to think of it is that someUnion ?? something returns a type where all the union members in the type of someUnion that are null or undefined are replaced with the type of something.

Maybe that replacement is null or undefined, and maybe it's something else entirely.

  • Related