I need to write a function like this:
const wrapper = (fn) => () => {
const value = fn.apply (this, arguments)
const somethingElseEntirely: WellDefinedType = doMagic (value)
return somethingElseEntirely
}
...that wraps any given function. It is known that given function returns a well defined type, say, string
. It is also known that given function can accept any combination of arguments, and the wrapped function should take the same arguments, however , it should return a different type of value.
Eg, a function like:
function foo (arg1: string, arg2?: number): string
...should become:
(arg1: string, arg2?: number): WellDefinedType
Is this possible to achieve in TypeScript without resorting to any
?
TypeScript 3.0 recently introduced new features allowing you do exactly this.
declare function wrapWithNumberReturn<A extends any[]>(fn: (...args: A) => any): (...args: A) => number
declare const concat: (a: string, b?: string) => string
// returns (a: string, b?: string) => number
const wrapped = wrapWithNumberReturn(concat)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.