【问题标题】:Difference between `Function` and `(...args: any[]) => any``Function` 和 `(...args: any[]) => any` 之间的区别
【发布时间】:2021-01-30 11:43:43
【问题描述】:

Function(...args: any[]) => any 有什么区别?

有趣的是,我刚刚注意到Function 不能分配给(...args: any[]) => any,但是为什么呢?

    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

【问题讨论】:

  • 你是对的。我现在在操场上试了一下,确实:它让我在=> any-typed 变量中使用=> never 函数。我会删除我的评论。
  • 好的,我当时也删除了我的 cmets。还是谢谢!

标签: typescript types


【解决方案1】:

显然Function 接口在其声明中没有可调用的签名。虽然如果你有一个Function 类型的对象,你可以将它称为如果它是(...args: any) => any 类型的。有一个(有些旧的)未解决的问题,microsoft/TypeScript#20007,要求对此进行更改。那里有一条评论says

Function 的初衷是不可调用。换句话说,函数类型的Function 应该像其他类型的unknown 一样,但不可调用。我们已经放宽了这个限制,通过特殊的大小写给Function 在编译器中一个可调用的行为。我们已经讨论过将其设为--noImplicitAny 错误,因为调用Functions 确实不安全。

如果您真的很在意这种情况,您可能想要解决该问题并给它您的 ? 并可能描述您的用例。不过,务实地说,它不太可能被改变,所以你最好只是注意到奇怪的差异并继续前进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-23
    • 2020-12-09
    • 1970-01-01
    • 2020-11-15
    • 2017-10-19
    • 1970-01-01
    • 2019-06-07
    相关资源
    最近更新 更多