我读了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
)的变量?
当接口遵循以下模式:
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
是这样的接口的例子。
这是因为在打字稿,您可以通过使用括号可调用签名接口定义函数类型。
接口能够描述所述宽范围的JavaScript对象可以采取的形状的。除了描述与属性的对象,接口还能够描述函数类型。
请参阅有关此功能的Typescript doc。
在你的情况identity
具有相同的签名通过GenericIdentityFn
中定义的类型,因为接口定义一个可调用签名采用类型T
的参数,并返回一个T
。