【问题标题】:Possible for typescript type to have a required field, but be optional on "constructor"?打字稿类型可能有一个必填字段,但在“构造函数”上是可选的?
【发布时间】: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,我不想更改同一个文件中的多个位置。由于我正在导出函数,所以我可以在任何地方使用它,所以我不想同时导出这两种类型。我也可以只在函数上内联类型,但它和以前有同样的问题。

遗憾的是,我必须执行两个次优选项之一,否则我的打字稿编译器会抱怨 notificationany 或不包含 category

必须有比这更好的方法。它是什么?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    这样的事情怎么样?您使用可选类别指定输入类型,然后导出具有所有必需属性的 Notification 类型。 Here's a working playground

    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'
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 2017-01-29
      • 2018-10-17
      • 2019-04-13
      • 2020-09-14
      • 2017-03-03
      • 2019-07-05
      相关资源
      最近更新 更多