[英]TypeScript: How to wrap a function, changing its return type?
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
. 众所周知,给定函数返回一个定义良好的类型,比如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中实现而不诉诸any
?
TypeScript 3.0 recently introduced new features allowing you do exactly this. TypeScript 3.0最近推出了新功能,允许您完成此操作。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.