ts 里面 使用 一个 函数当做参数并且有返回值 ?

下面的代码会有类型问题, 因为返回值使用的是 或 不能精准赋给 string

monthDates(year: number, month: number, dayFormatter?: (d: Date) => string | Date | number): Array<Week>

const list: string[] = c.monthDates(2022, 1, d => `${d.getDate()}`)

image.png

阅读 3.1k
4 个回答

函数 monthDates 返回类型是 Week[], 你用 string[] 去接,所以报错了

如上所说,改成 const list = c.monthDates(2022, 1, d => `${d.getDate()}`)就好了,跟第三个参数没关系把

你这么玩儿只能
const list: string[] = c.monthDates(...) as any as string[];
其实你不给list指定类型就好了,或者就是const list: Week[];

没什么特别好说的,你的思路还不适应TS,而且代码的边界也不清晰。

定义 monthDates 函数的时候加个重载:

type Week = string | number | Date;

declare function monthDates<T extends any>(year: number, month: number, dayFormatter: (r: Date) => T): T[];
declare function monthDates(year: number, month: number): Week[];
declare function monthDates<T extends any>(year: number, month: number, dayFormatter?: (r: Date) => T): T[] | Week[];

就没啥问题了:
image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进