【发布时间】:2023-01-12 10:31:55
【问题描述】:
尝试使用带有必填字段的类型,因为每个字段都是必需的,但默认其中一个参数,因此我不必每次都键入它。例如:
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,我不想更改同一个文件中的多个位置。由于我正在导出函数,所以我可以在任何地方使用它,所以我不想同时导出这两种类型。我也可以只在函数上内联类型,但它和以前有同样的问题。
遗憾的是,我必须执行两个次优选项之一,否则我的打字稿编译器会抱怨 notification 是 any 或不包含 category。
必须有比这更好的方法。它是什么?
【问题讨论】:
标签: typescript typescript-typings