给定以下类型
enum Modes {
error,
warning
}
type Notification = {
title: string;
text: string;
};
type CustomNotification = Notification & { mode: Modes };
interface Options {
defaultNotification: Notification;
customNotification?: CustomNotification;
}
我想将一个变量分配给customNotification
(如果可用(,否则分配给defaultNotification
,因此我在赋值中使用逻辑 OR 运算符,如下所示:
const notification = customNotification || notificationDefault;
然后我想根据mode
的值(如果可用(有条件地执行逻辑。
if (notification.mode && notification.mode !== Modes.error) { /** code here */ }
但是,notification
只分配给类型Notification
而不是CustomNotification | Notification
,因此打字稿在尝试读取值时会抛出错误notification.mode
Property 'mode' does not exist on type 'Notification'.
我什至尝试将notification
类型显式分配给CustomNotification | Notification
但这不起作用。
我不明白为什么这不起作用,我想知道除了重构我的代码以使用两个变量之外,是否有其他解决方法?
主要问题是mode
是一个在工会的一个成员中不存在Notification | CustomNotification
字段。不允许检查mode
字段以查找正在Notification
的对象,因为它没有此类字段。下面我的主张如何处理你的问题。
解决方案一 - 使用默认模式进行类型统一
我会考虑不要在这里使用双重类型,而是使用一种类型,并在Modes
内部引入一些中性元素,比如说 -default
,当我们这样做时,所有类型的问题都会消失,我们不需要做任何类型断言或保护。考虑:
enum Modes {
error,
warning,
default, // neutral value
}
type Notification = {
title: string;
text: string;
mode: Modes;
};
interface Options {
defaultNotification: Notification;
customNotification?: Notification;
}
// getting active notification helper
const getNotification = (options: Options): Notification => {
return options.customNotification ?? options.defaultNotification;
}
// using
const notification = getNotification(options);
if (notification.mode !== Modes.error) { /** code here */ }
我们唯一需要做的就是defaultNotification
设置为具有相等mode
Modes.defalut
的对象。
解决方案二 - 模式作为显式未定义字段
最终,如果您想保持Modes
的当前形状,我们可以引入mode
字段作为defaultNotification
中的undefined
字段。请考虑以下事项:
type BaseNotification = {
title: string;
text: string;
};
type DefNotification = BaseNotification & { mode?: undefined } // pay attention here
type CustomNotification = BaseNotification & { mode: Modes }
type Notification = DefNotification | CustomNotification;
interface Options {
defaultNotification: DefNotification;
customNotification?: CustomNotification;
}
const getNotification = (options: Options): Notification => {
return options.customNotification ?? options.defaultNotification;
}
这里的重点是{ mode?: undefined }
,我们说我们的DefNotification
有mode
字段,但它唯一可能的值是undefined
。