【问题标题】:Why can I assign a `Function` to an `Interface` in Typescript?为什么我可以在 Typescript 中将 `Function` 分配给`Interface`?
【发布时间】:2019-07-04 10:23:22
【问题描述】:

我正在阅读Typescript Handbook - Generics,其中有一段代码如下:

interface GenericIdentityFn {
    <T>(arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity;

我想知道为什么我可以将identity(即Function)分配给类型为GenericIdentityFn(即Interface)的变量?

【问题讨论】:

  • 因为接口是函数的?它具有可调用签名,如in the interface docs 所述。
  • @jonrsharpe 为什么不添加这个作为答案,看起来不错:)
  • @TitianCernicova-Dragomir 因为这是官方文档中解释的重言式?函数符合接口,因为它是函数的接口。

标签: javascript typescript function interface


【解决方案1】:

当接口遵循这种模式时:

interface Callable {
  (): any
}

据说任何实现这个接口的东西都是可调用的或有调用签名的。这是描述函数和方法的一种奇特方式。该符号还有其他变体:

interface GenericCallable<T> {
  (): T
}
interface Newable {
  new (): any
}
interface GenericNewable<T> {
  new (): T
}

带有new 关键字的那些是newable,这意味着它们是使用new 关键字调用的(类似于类)。

你也可以同时拥有一个callablenewable的接口。标准库中内置的Date 对象就是其中之一:

interface DateConstructor {
    new(): Date;
    (): string;
}

长话短说,接口也可以描述功能,GenericIdentityFn 就是这样一个接口的一个例子。

【讨论】:

    【解决方案2】:

    这是因为在 Typescript 中,您可以通过带有可调用签名的接口使用括号定义函数类型。

    接口能够描述 JavaScript 对象可以采用的各种形状。除了用属性描述对象外,接口还能够描述函数类型。

    请参阅Typescript doc 了解此功能。

    在您的情况下,identityGenericIdentityFn 定义的类型具有相同的签名,因为接口定义了一个可调用签名,该签名接受T 类型的参数并返回T

    【讨论】:

      猜你喜欢
      • 2012-11-10
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多