gpt4 book ai didi

TypeScript:如何包装一个函数,改变它的返回类型?

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:25 25 4
gpt4 key购买 nike

我需要写一个这样的函数:

const wrapper = (fn) => () => {
const value = fn.apply (this, arguments)
const somethingElseEntirely: WellDefinedType = doMagic (value)
return somethingElseEntirely
}

...包装任何给定的函数。众所周知,给定的函数会返回一个定义明确的类型,比如 string。众所周知,给定函数可以接受任何参数组合,包装函数应该采用相同的参数,但是,它应该返回不同类型的值。

例如,像这样的函数:

function foo (arg1: string, arg2?: number): string

...应该变成:

(arg1: string, arg2?: number): WellDefinedType

这是否可以在不借助 any 的情况下在 TypeScript 中实现?

最佳答案

TypeScript 3.0 recently introduced new features让你做到这一点。

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

关于TypeScript:如何包装一个函数,改变它的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51996138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com