我为什么可以分配一个`Function`到`Interface`在打字稿?

问题描述 投票:1回答:2

我读了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)的变量?

javascript typescript function interface
2个回答
3
投票

当接口遵循以下模式:

interface Callable {
  (): any
}

它说,任何实现这个接口是可调用或具有呼叫签名。它描述的功能和方法奇特的方式。有迹象表明,符号的其他变化:

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

其中,与所述new关键字的那些是newable,这意味着它们使用的是new关键字(如班)调用。

您也可以有一个接口,它是可调用和newable在同一时间。内置的标准库的Date对象就是其中之一:

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

总而言之,接口还可以描述功能和GenericIdentityFn是这样的接口的例子。


1
投票

这是因为在打字稿,您可以通过使用括号可调用签名接口定义函数类型。

接口能够描述所述宽范围的JavaScript对象可以采取的形状的。除了描述与属性的对象,接口还能够描述函数类型。

请参阅有关此功能的Typescript doc

在你的情况identity具有相同的签名通过GenericIdentityFn中定义的类型,因为接口定义一个可调用签名采用类型T的参数,并返回一个T

© www.soinside.com 2019 - 2024. All rights reserved.