given the following types
enum Modes {
error,
warning
}
type Notification = {
title: string;
text: string;
};
type CustomNotification = Notification & { mode: Modes };
interface Options {
defaultNotification: Notification;
customNotification?: CustomNotification;
}
I want to assign a variable to customNotification if available, otherwise to defaultNotification, hence I use the logical OR operator in assignment, as:
const notification = customNotification || notificationDefault;
then I want to conditionally execute logic depending on the value of mode if available.
if (notification.mode && notification.mode !== Modes.error) { /** code here */ }
However, notification is only assigned to type Notification rather than CustomNotification | Notification, thus typescript throws an error when trying to read notification.mode value Property 'mode' does not exist on type 'Notification'.
I have even tried to explicitly assign notification type to CustomNotification | Notification but that did not work.
I don't see why this isn't working, and I wonder if there's a workaround other than refactoring my code to use two variables instead?