Typescript: Function should be assignable to (...args: any[]) => any

Created on 14 Nov 2017  ·  2Comments  ·  Source: microsoft/TypeScript

Obviously all functions have type Function. And likewise all functions can be given the type

type AnyFunc = (...args: any[]) => any;

AFAIK, there is nothing one can do with something of type Function that cannot be done with something of type AnyFunc and vice versa. However they are not equivalently assignable:

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

If I edit lib.d.ts to add a callable signature to Function:

interface Function {
  (...argArray: any[]): any;
  //...
}

it seems to "fix" this issue; is there any reason not to make this change for real?

In Discussion Suggestion

Most helpful comment

@mhegazy What's the benefit of such behavior, rather than treating Function as identical to (...args: any[]) => any? 🤔

I have a similar question about object and { [key: keyof any]: any } not being treated as identical.

All 2 comments

The original intention of Function is to not be callable. in other words, Function to function types should be like unknown to other types, but not callable. we have since relaxed this restriction giving Function a callable behavior in the compiler through special casing. We have talked about making this a --noImplicitAny error since, it is really unsafe to call Functions.

@mhegazy What's the benefit of such behavior, rather than treating Function as identical to (...args: any[]) => any? 🤔

I have a similar question about object and { [key: keyof any]: any } not being treated as identical.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

manekinekko picture manekinekko  ·  3Comments

fwanicka picture fwanicka  ·  3Comments

weswigham picture weswigham  ·  3Comments

siddjain picture siddjain  ·  3Comments

bgrieder picture bgrieder  ·  3Comments