#Opposite of `??` operator?

18 messages · Page 1 of 1 (latest)

limpid island
#

I have long been in the habit of using || and && to write conditional assignments.

The ?? operator was awesome because it only executes the right-hand if the left-hand is null or undefined, not any falsy values, like ||.

Is there something similar for &&, where it executes the right-hand only if the left hand is not null or undefined?

limpid island
#
if (printOnExecute("hi", "") && printOnExecute("bye")) {
  console.log("hi was executed") // Does't get here cause "" short-circuits "bye"
}
#

Yes that's exactly what I was asking

#

And yeah I was wondering if there was a short cut so I don't have to explicitly write out that check. (BTW != null is enough, as both undefined and null == null but not falsy values)

#

And the other more annoying problem is... then it resolves a boolean in the expression. I don't want that.

#
declare const id: string | null;
declare const map: Record<string, {}>;
const obj = id != null && map[id]; // `obj = false | {}` but I want `obj = {} | null`
const obj2 = id && map[id]; // `obj = {} | "" | null` but I want `obj = {} | null`
analog wren
#

id ? map[id] : null

limpid island
#

@analog wren That has the same issue with "" being falsy

analog wren
#

Sure, then id != null ? map[id] : null

limpid island
#

Thanks, am aware of that, not what I'm looking for 🙂 See above

analog wren
#

I'm really confused, your original question was answered, which was null/undefined and the answer is most certainly ??

harsh juniper
#

you can see that an opposite to ?? isn't there

#

and typescript doesn't add any operators because it doesn't do runtime stuff

#

(technically it adds the non-null assertion foo! but that disappears when compiling)

limpid island
#

@analog wren My original questions was about an operator that is the inverse of ??. The first answer is wrong, && is not an inverse because it also steps over falsy values, not just null or undefined. I am aware of more verbose code like using an explicit ternary, but that's exactly what I want a terse operator for, just like ?? eliminated the need for str != null ? str : "default" .

#

@harsh juniper Thanks, I guess I could learn to read the operators reference 🙂 That confirms it doesn't exist. I'm trying to find a workaround with user defined typeguards but since they force you to return a boolean value it has the same issue with clobbering falsy values...