简体   繁体   English

TypeScript:如何包装函数,更改其返回类型?

[英]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)

Playground here 这里的游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeScript 如何用不同的泛型返回类型包装函数? - TypeScript how to wrap function with different generic return type? 打字稿:包装函数返回泛型类的类型 - Typescript: Wrap function return type of generic class 我如何让 typescript 根据 function2E977777777777777777777777777777777777777777777777777777777777777777777777777777777777BED18 的返回类型 functionC17A94F14Z 的返回类型来推断 function 的返回类型 - How do I get typescript to infer the return type of a function based on the return type on a function of its arguments 在TypeScript中,如何根据其参数之一的返回类型来确定函数的返回类型? - In TypeScript, how do I make a function's return type based on the return type of one of its arguments? 如果 function 将超类作为其返回类型,TypeScript 是否可以返回子类? - Can TypeScript return the subclass if a function has the superclass as its return type? TypeScript 映射从其参数类型返回函数的类型 - TypeScript mapping return type of a function from its argument type 如何在TypeScript中包装带有承诺的返回类型? - How do I wrap a return type with a promise in TypeScript? 如何键入需要返回对象副本同时更改其属性之一的类型的函数? - How to type a function that needs to return a copy of an object while also changing the type of one of its properties? 根据 TypeScript 中的参数在字典中定义 function 的返回类型 - Define return type of a function in dictionary based on its parameter in TypeScript 使用 TypeScript 使函数的返回类型取决于其参数? - Make return type of function depends on its arguments with TypeScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM