The nullish coalescing operator DOES NOT apply to this case:
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
See the docs
In this case you have a simple union of type Day | 0, you just have to check manually:
for (let i = 0; i < 4; i++) {
const item = daysArray[i];
if (typeof item === "number") {
console.log(0);
} else {
console.log(item.dayNumber);
}
}
Answer from Nullndr on Stack OverflowVideos
The nullish coalescing operator DOES NOT apply to this case:
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
See the docs
In this case you have a simple union of type Day | 0, you just have to check manually:
for (let i = 0; i < 4; i++) {
const item = daysArray[i];
if (typeof item === "number") {
console.log(0);
} else {
console.log(item.dayNumber);
}
}
The nullish coalescing does not apply in this case, here is documentation of nullish coalescing with examples of how it's supposed to be used: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
The reason why your code is giving red squiggly is because the element at daysArray[i] might be either a number or an object which has the shape of the Day interface. so trying to access daysArray[i].dayNumber is not entirely correct, first you have to check that it's an object and not a number. this way typescript compiler will infer the type of daysArray[i] to be of type Day and will allow you to access dayNumber property.
Here is a working example:
type Day = {
dayNumber: number;
color: string;
isBooked: boolean;
};
const myDay: Day = {
dayNumber: 12,
color: "blue",
isBooked: false
};
const daysArray: (Day | 0)[] = [0, 0, 0, myDay];
for (let i = 0; i < daysArray.length; i++) {
const element = daysArray[i];
if(typeof element === 'object') {
console.log(element.dayNumber);
}
}
Please refer to the official documentation for type narrowing: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards
Take this interface for example
interface Item {
value?: number
}Which among the two do you prefer if you will be accessing the value property of an item and why?
console.log(item.value ?? 1.00) // 1.00 is the fallback value
console.log(item.value || 1.00) // 1.00 is the fallback value
Personally, I prefer to use the nullish coalescing operator ?? for fallback values since it's more explicit and it sames me from the weird falsy values that JavaScript has.
Yes. As of TypeScript 3.7 (released on November 5, 2019), this feature is supported and is called Optional Chaining:
At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a
nullorundefined. The star of the show in optional chaining is the new?.operator for optional property accesses.
Refer to the TypeScript 3.7 release notes for more details.
Prior to version 3.7, this was not supported in TypeScript, although it was requested as early as Issue #16 on the TypeScript repo (dating back to 2014).
As far as what to call this operator, there doesn't appear to be a consensus. In addition to "optional chaining" (which is also what it's called in JavaScript and Swift), there are a couple of other examples:
- CoffeeScript refers to it as the existential operator (specifically, the "accessor variant" of the existential operator):
The accessor variant of the existential operator
?.can be used to soak up null references in a chain of properties. Use it instead of the dot accessor.in cases where the base value may be null or undefined.
- C# calls this a null-conditional operator.
a null-conditional operator applies a member access,
?., or element access,?[], operation to its operand only if that operand evaluates to non-null; otherwise, it returnsnull.
- Kotlin refers to it as the safe call operator.
There are probably lots of other examples, too.
It is now possible, see answer of user "Donut".
Old answer: Standard JavaScript behaviour regarding boolean operators has something that may help. The boolean methods do not return true or false when comparing objects, but in case of OR the first value that is equal to true.
Not as nice as a single ?, but it works:
var thing = foo && foo.bar || null;
You can use as many && as you like:
var thing = foo && foo.bar && foo.bar.check && foo.bar.check.x || null;
Default values are also possible:
var name = person && person.name || "Unknown user";
Update
JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.
Old Answer
Please check compatibility before using it.
The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):
var whatIWant = someString || "Cookies!";
There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.
Clarification
Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:
alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
This means:
var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
function coalesce() {
var len = arguments.length;
for (var i=0; i<len; i++) {
if (arguments[i] !== null && arguments[i] !== undefined) {
return arguments[i];
}
}
return null;
}
var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);
// xyz.val now contains 5
this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.