打字稿类型可能具有必填字段,但在"constructor"上是可选的?



尝试使用一个具有必需字段的Type,因为每个字段都是必需的,但是默认一个参数,因此我不必每次都键入它。例如:

export type Notification = {
title: string
message: string
category: 'good' | 'bad'
}
const notifications: Notification[] = []
export const notify = (notification) => {
notifications.push(notification)
}

所以对于伪构造函数,一开始看起来Notification是一个很好的输入类型。

export const notify = (notification: Notification) => {
notifications.push(notification)
}

但是,如果category在绝大多数情况下都是good呢?然后我想使category键可选的功能,并默认为good。但是,由于类型的原因,需要category。我该怎么解决这个问题?

我可以创建一个新类型:
export type NotifyInput = {
title: string
message: string
category?: 'good' | 'bad'
}
export const notify = (notification: NotifyInput) => {
notifications.push({
...notification,
category: notification.category ?? 'good'
})
}

,但这根本不是DRY,我不想在同一个文件中改变多个点。因为我要导出函数,所以我可以在任何地方使用它,所以我不想同时导出两种类型。我也可以将类型内联到函数中,但是它有和以前一样的问题。

遗憾的是,我不得不做两个次优选项之一,或者我的typescript编译器抱怨notificationany类型或不包含category

一定有比这更好的方法。这是什么?

这样怎么样?您使用一个可选的类别指定输入类型,然后导出具有所有所需属性的Notification类型。这是一个工作的操场。

type NotificationInput = {
title: string
message: string
category?: 'good' | 'bad'
}
export type Notification = Required<NotificationInput>;
const notifications: Notification[] = []
export const notify = (notification: NotificationInput) => {
notifications.push({
...notification,
category: notification.category || 'good'
})
}

相关内容

最新更新