【问题标题】:TypeScript: How to wrap a function, changing its return type?TypeScript:如何包装一个函数,改变它的返回类型?
【发布时间】:2018-08-24 09:13:41
【问题描述】:

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

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

这是否可以在 TypeScript 中实现而不诉诸 any

【问题讨论】:

    标签: typescript


    【解决方案1】:

    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

    【讨论】:

    • 截至 2018 年 8 月,从 2.8 迁移到 TypeScript 3.0 是否容易且合理?
    • 除了新功能之外,这两个版本之间没有太多变化,所以我想说这可能不会太难
    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2020-08-31
    • 2018-02-23
    • 2015-04-30
    相关资源
    最近更新 更多