Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `Function` and `(...args: any[]) => any`

What is the difference between Function and (...args: any[]) => any?

Interestingly, I just noticed that Function is not assignable to (...args: any[]) => any, but why?

    declare let foo: Function;
    declare let bar: (...args: any[]) => any;
    bar = foo;
//  ~~~
//  ^^^
//  Type 'Function' is not assignable to type '(...args: any[]) => any'.
//    Type 'Function' provides no match for the signature '(...args: any[]): any'. (2322)

Playground

like image 419
Pedro A Avatar asked Oct 15 '20 23:10

Pedro A


1 Answers

Apparently the Function interface doesn't have a callable signature in its declaration. Although if you have an object of type Function, you're allowed to call it if it were of type (...args: any) => any. There is a (somewhat old) open issue, microsoft/TypeScript#20007, asking for this to be changed. There's a comment there which says:

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.

If you really care about this situation, you might want to go to that issue and give it your 👍 and possibly describe your use case. Pragmatically speaking, though, it's unlikely to be changed, so you're probably better off just noting the weird discrepancy and moving on.

like image 60
jcalz Avatar answered Sep 28 '22 07:09

jcalz