TypeScript:为什么不能将`函数`分配给`(... args:any [])=> any`?

时间:2017-09-20 08:42:12

标签: typescript

declare var a: (...args: any[]) => any;
declare var b: Function;
a = b;

// Error:
// Type 'Function' is not assignable to type '(...args: any[]) => any'.
//  Type 'Function' provides no match for the signature '(...args: any[]): any'

尽管使用类型Function几乎不是一个好主意,但我希望我写的类型定义与此类型兼容。特别是,当Function传递给通用函数时:

declare function foo<T>(bar: (...args: any[]) => T): T;
declare var baz: Function;
foo(baz);

它失败并出现相同的错误,但期望它起作用并将T推断为any

似乎是合理的

1 个答案:

答案 0 :(得分:2)

您可以尝试以下内容:

interface FunctionWithTypedReturn<T> extends Function {
    (...args: any[]): T;
}

declare function foo<T>(bar: FunctionWithTypedReturn<T>): T;

declare var baz: FunctionWithTypedReturn<number>;

foo(baz);