[英]typescript: How would you return a new function with the same arguments but different types for those arguments?
const stringToDate = ( x: string ) => new Date( x )
// stringToDate: (x: string) => Date
type MapTupleValues<Tuple extends any[], NewValue> = {
[ index in keyof Tuple ]: NewValue
}
type TestMappedTuple = MapTupleValues<[ a: Date, b: Date ], string>
// TestMappedTuple = [a: string, b: string]
// works fine
function modifyFn<Fn extends ( ...args: Date[] ) => any> ( fn: Fn ) {
return ( ...args: MapTupleValues<Parameters<Fn>, string> ): ReturnType<Fn> => {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error
// A rest parameter must be of an array type.
return fn( ...args.map( x => stringToDate( x ) ) )
}
}
const daysDifference = ( start: Date, end: Date ) => ( end.getTime() - start.getTime() ) / ( 1000 * 60 * 60 * 24 )
// daysDifference: (start: Date, end: Date) => number
const modifiedDaysDifference = modifyFn( daysDifference )
// modifiedDaysDifference: (start: string, end: string) => number
console.log( daysDifference( new Date( '2022-07-29' ), new Date( '2022-08-21' ) ) ) // 23
console.log( modifiedDaysDifference( '2022-07-29', '2022-08-21' ) ) // 23
this seems to be working, even though there is an error in modifyFn
这似乎有效,即使
modifyFn
有错误
how can I get rid of the error while still getting the same result?如何在获得相同结果的同时摆脱错误?
Thanks jcalz谢谢 jcalz
Here's their answer:这是他们的答案:
const stringToDate = (x: string) => new Date(x)
// stringToDate: (x: string) => Date
type MapTupleValues<T extends any[], V> = Extract<{
[I in keyof T]: V
}, any[]>
type TestMappedTuple = MapTupleValues<[a: Date, b: Date], string>
// TestMappedTuple = [a: string, b: string]
// works fine
function modifyFn<Fn extends (...args: Date[]) => any>(fn: Fn) {
return (...args: MapTupleValues<Parameters<Fn>, string>): ReturnType<Fn> => {
return fn(...args.map(x => stringToDate(x)))
}
}
const daysDifference = (start: Date, end: Date) => (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)
// daysDifference: (start: Date, end: Date) => number
const modifiedDaysDifference = modifyFn(daysDifference)
// modifiedDaysDifference: (start: string, end: string) => number
console.log(daysDifference(new Date('2022-07-29'), new Date('2022-08-21'))) // 23
console.log(modifiedDaysDifference('2022-07-29', '2022-08-21')) // 23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.