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