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

时间:2018-08-24 01:03:06

标签: typescript

我需要编写如下函数:

// not sure if isLandscape() is meant to be global    
let landscape: boolean = true;
function isLandscape() {
  return landscape;
}

const variantVector = makeVariant(isLandscape, new Vector(1, 2), new Vector(3, 4));

landscape = true;
console.log(variantVector.x, variantVector.y) // 1, 2
landscape = false;
console.log(variantVector.x, variantVector.y) // 3, 4

...包装任何给定的函数。已知给定函数返回定义明确的类型,例如const wrapper = (fn) => () => { const value = fn.apply (this, arguments) const somethingElseEntirely: WellDefinedType = doMagic (value) return somethingElseEntirely } 。还已知给定函数可以接受参数的任何组合,并且包装的函数应采用相同的参数,但是,它应返回不同类型的值。

例如,类似这样的函数

string

...应成为:

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

是否可以在TypeScript中实现而无需借助(arg1: string, arg2?: number): WellDefinedType

1 个答案:

答案 0 :(得分:4)

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