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
Difference between call signature and function type
提问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 myOne
and myTwo
variables effectively the same. They are (as far as I can see) of the very same type, just defined differently.
在这段代码中myOne
和myTwo
变量有效地相同。它们(据我所知)属于相同的类型,只是定义不同。
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)=>number
signature is useful as a property
annotation :
该(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 property
annotation.
property
注释不支持哪个。