typescript 调用签名和函数类型的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32043487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:04:11  来源:igfitidea点击:

Difference between call signature and function type

typescript

提问by Andrew Savinykh

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

In this code myOneand myTwovariables effectively the same. They are (as far as I can see) of the very same type, just defined differently.

在这段代码中myOnemyTwo变量有效地相同。它们(据我所知)属于相同的类型,只是定义不同。

Now when we are using interface for defining them we use call signaturethat 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?

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

回答by basarat

They are exactly the same.

它们完全一样。

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

为什么我们需要两种不同但又如此相似的方式在打字稿中写出同样的东西

The (x:number, y:number)=>numbersignature is useful as a propertyannotation :

(x:number, y:number)=>number签名是一个有用的property注释:

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

Which is similar to your:

这类似于您的:

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

Just a shorthand for a verbose:

只是verbose的简写:

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

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

所以你可以看到()=>.

Also

One thing to note is that a functionsignature allows overloading:

需要注意的一件事是函数签名允许重载

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

Which is not supported for a propertyannotation.

property注释不支持哪个。