调用签名和函数类型的区别 [英] Difference between call signature and function type

查看:32
本文介绍了调用签名和函数类型的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么我们对调用签名和函数类型有不同的语法.考虑以下代码:

I'm trying to understand why we have different syntax for call signatures and for function types. Consider the following code:

interface MyInterface {
   // This is call signature
   // It is used inside object type, function expression, function declaration, etc...
    (x:number, y:number):number; 
}

var myOne : MyInterface = (x,y) => x + y;
            // vv this is function type
var myTwo : (x:number, y:number)=>number = (x,y) => x + y; 
// function type is used in function type literal

在这段代码中,myOnemyTwo 变量实际上是相同的.它们(据我所知)属于完全相同的类型,只是定义不同.

In this code myOne and myTwo variables effectively the same. They are (as far as I can see) of the very same type, just defined differently.

现在,当我们使用接口定义它们时,我们使用调用签名,如下所示:

Now when we are using interface for defining them we use call signature that looks like this:

(x:number, y:number):number

当我们不使用接口时,我们使用函数类型文字:

When we are not using interface we use function type literal:

(x:number, y:number)=>number

两者都表达相同的东西,参数的名称和类型以及返回类型的类型.我想知道,为什么我们需要两种不同但又如此相似的方式在打字稿中写出同样的东西?

Both express the same thing, names and types of parameters and types of the return type. I would like to know, why do we need two different yet so similar ways to write the same thing in typescript?

推荐答案

它们完全一样.

为什么我们需要两种不同但又如此相似的方式在打字稿中编写相同的内容

why do we need two different yet so similar ways to write the same thing in typescript

(x:number, y:number)=>number 签名可用作 property 注释:

The (x:number, y:number)=>number signature is useful as a property annotation :

interface MyInterface {
    (x:number, y:string):string;   
    someProperty: (x:number, y:number)=>number;
}

与您的相似:

var myTwo : (x:number, y:number)=>number

只是一个详细的简写:

var myTwo : {(x:number, y:number):number}

所以你可以看到 ()=> 的简单性.

So you can see the simplicity of ()=>.

需要注意的一点是函数签名允许重载:

One thing to note is that a function signature allows overloading:

var myTwo : {
    (x:number, y:number):number;
    (x:number):string;
}

property 注释不支持.

这篇关于调用签名和函数类型的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆