The nullish coalescing operator does not work in this specific scenario. To understand how it should be used, check out the documentation which provides examples: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
If you're seeing red squiggly lines in your code, it's because the element at daysArray[i]
could be a number or an object that follows the structure of the Day
interface. Therefore, you need to verify if it's an object before trying to access daysArray[i].dayNumber
. By doing this, TypeScript will recognize the type of daysArray[i]
as Day
, allowing you to access the dayNumber
property.
Below is an example illustrating this:
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);
}
}
For more information on type narrowing, refer to the official TypeScript documentation: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards