在 Typescript 中使用 FP 时,我转向了重载函数,现在遇到了 Typescript 无法检测到正确的重载参数类型的问题。
/** parses as `Date` instance */
export function asDate(val: string | number | Date): Date;
export function asDate(val: string | number | Date | null | undefined): Date | null;
export function asDate(val: unknown) {
return val instanceof Date ? val : typeof val === 'number' || typeof val === 'string' ? new Date(val) : null;
}
export function apply<T, R>(fn: (arg: T) => R) {
return fn;
}
const date0 = asDate(123); // detected as Date
const date1 = apply(asDate)(123); // detected as Date | null
我希望
date1
推断它是用 number
调用的,并检测返回类型 Date
,但它采用最开放的类型并检测 Date | null
。有办法解决吗?
实际上,这是可能的,尽管我不太确定为什么你的方法不起作用。
它的工作原理是让编译器推断传递函数的类型:
export function apply<F extends (args: any) => any>(fn: F) {
return fn;
}
最后:
/** parses as `Date` instance */
export function asDate(val: string | number | Date): Date;
export function asDate(val: null | undefined): null;
export function asDate(val: unknown) {
return val instanceof Date ? val : typeof val === 'number' || typeof val === 'string' ? new Date(val) : null;
}
export function apply<F extends (args: any) => any>(fn: F) {
return fn;
}
const date0 = asDate(123); // detected as Date
const date1 = apply(asDate)(123); // detected as Date
const date2 = asDate(null); // detected as null
const date3 = apply(asDate)(null); // detected as null
const date4 = apply(asDate)(true); // TS2769: No overload matches this call