我需要编写如下函数:
// 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
?
答案 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)