下面的代码会有类型问题, 因为返回值使用的是 或 不能精准赋给 string
monthDates(year: number, month: number, dayFormatter?: (d: Date) => string | Date | number): Array<Week>
const list: string[] = c.monthDates(2022, 1, d => `${d.getDate()}`)
下面的代码会有类型问题, 因为返回值使用的是 或 不能精准赋给 string
monthDates(year: number, month: number, dayFormatter?: (d: Date) => string | Date | number): Array<Week>
const list: string[] = c.monthDates(2022, 1, d => `${d.getDate()}`)
如上所说,改成 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[];
就没啥问题了:
函数
monthDates
返回类型是Week[]
, 你用string[]
去接,所以报错了