通过逻辑运算符分配变量值的打字稿仅使用后一种类型



给定以下类型

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.modeProperty '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设置为具有相等modeModes.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 },我们说我们的DefNotificationmode字段,但它唯一可能的值是undefined

相关内容

最新更新