You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何为带separator参数的日期组件定义类型

为getCurrentDate方法添加TypeScript类型定义

你这个方法逻辑非常简单,类型标注没有复杂的点,核心处理好参数和返回值的类型即可:

  • 入参separator你已经设置了默认值为空字符串,它本身就是用来做拼接的字符串,直接标注为string类型即可。TS其实也能通过默认值自动推导出这个参数的类型,不过显式标注可读性更好。
  • 方法最终返回拼接完成的格式化日期字符串,返回值标注为string即可。

另外你现有实现里有个小逻辑漏洞:处理日期的时候没有像月份那样做补0处理,比如当月第3天会直接返回数字3而不是补0后的03,会导致日期格式长度不统一,我在带类型的版本里顺手修复了:

export function getCurrentDate(separator: string = ''): string {
  const newDate = new Date()
  const date = newDate.getDate();
  const month = newDate.getMonth() + 1;
  const year = newDate.getFullYear();

  // 统一给月、日做补0处理
  const formatNum = (num: number) => num < 10 ? `0${num}` : `${num}`
  
  return `${year}${separator}${formatNum(month)}${separator}${formatNum(date)}`
}

如果你想让类型校验更严格,避免传入不符合预期的分隔符,还可以用字符串字面量联合类型限制separator的可选值,比如只允许传入常用的日期分隔符:

type DateSeparator = '-' | '/' | '.' | ''
export function getCurrentDate(separator: DateSeparator = ''): string {
  const newDate = new Date()
  const date = newDate.getDate();
  const month = newDate.getMonth() + 1;
  const year = newDate.getFullYear();
  const formatNum = (num: number) => num < 10 ? `0${num}` : `${num}`
  return `${year}${separator}${formatNum(month)}${separator}${formatNum(date)}`
}

这种写法下,如果你传了分隔符可选范围外的值(比如传字母a),TS会直接抛出类型错误,提前拦截不合法的参数。


内容的提问来源于stack exchange,提问作者sheeba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 06:54:27