thorn0
thorn0

Reputation: 10417

TypeScript: why isn't `Function` assignable to `(...args: any[]) => any`?

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'

Even though it's almost never a good idea to use the type Function, I want the type definitions I write to be compatible with this type. In particular, when Function is passed to a generic function:

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

It fails with the same error whereas it seems reasonable to expect it to work and to infer T to be any

Upvotes: 3

Views: 1275

Answers (1)

Remo H. Jansen
Remo H. Jansen

Reputation: 24979

You could try something like the following:

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

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

declare var baz: FunctionWithTypedReturn<number>;

foo(baz);

Upvotes: 2

Related Questions