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.
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?
A function signature (or type signature, or method signature) defines input and output of functions or methods. A signature can include: parameters and their types. a return value and type. exceptions that might be thrown or passed back.
Call Signatures In JavaScript, functions can have properties in addition to being callable. However, the function type expression syntax doesn't allow for declaring properties. If we want to describe something callable with properties, we can write a call signature in an object type: type DescribableFunction = {
Today I will describe how to write type signatures for a wide range of javascript functions. This will help readers narrow types, increase reliability, type dependencies, and more. A type signature is like a blueprint for any given segment of code.
C++ Reference. Programming Terms. Function Signatures. A function signature consists of the function prototype. What it tells you is the general information about a function, its name, parameters, what scope it is in, and other miscellaneous information.
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 :
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 :
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;
}
Which is not supported for a property
annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With