如何传入使用 "this | that | other thing" 语法定义的 prop 的值?



我有以下映射器函数,我试图在JSX prop中指定一个值,但类型定义不允许我传递该值。下面是代码…

function mapper(notification: NotificationMessageType) {
let style = "info";
switch (notification.icon) {
case NotificationIconEnum.Error:
style = "error";
break;
case NotificationIconEnum.Warning:
style = "warning";
break;
}
return (
<Notification
key={notification.id}
type={{ style: style }}
closable={true}
onClose={() => notificationContext.close(notification.id)}>
<span>{notification.message}</span>
</Notification>
);
}

抱怨的prop是代码段底部Notification组件的typeprop。typeprop定义为…

type?: {
style?: 'none' | 'success' | 'error' | 'warning' | 'info';
icon?: boolean;
};

但是我传入一个string会导致TypeScript说它不是一个兼容的类型。

既然我不能从Notification导入该类型定义,我如何传递值?

编辑:

顺便说一下,错误信息显示…

类型'string'不能赋值给类型' info"|"error"|"warning"|"none"| "success"'.ts(2322)通知。ts(57,9):预期Type来自属性style它在Type{中声明风格吗?:";info"|"error"|"warning"|"none"|"success";图标?:布尔;} '

您可以将style变量定义为以下类型:

let style: 'error' | 'warning' | 'info' = 'info';

将其放入函数中会更简洁,并避免switch作为奖励:

const getStyle = (icon: NotificationIconEnum) => {
if (icon === NotificationIconEnum.Error) return 'error';
if (icon === NotificationIconEnum.Warning) return 'warning';
return 'info';
};
function mapper(notification: NotificationMessageType) {
return (
<Notification
key={notification.id}
type={{ style: getStyle(notification.icon) }}
closable={true}
onClose={() => notificationContext.close(notification.id)}>
<span>{notification.message}</span>
</Notification>
);
}

这样TS就可以自动推断出所需的类型,而不会产生额外的类型噪声。

最新更新