Function Type & Callback In TypeScript

in Programming & Dev2 months ago

Function Type & Callback In TypeScript

<p dir="auto"> What if we could use functions as a special type? Let me make my point clearer.Consider the following two functions: <pre><code>function add(n1: number, n2: number): number { return n1 + n2; } function printResult(num: number): void { console.log('Result: ' + num); <p dir="auto"> Now suppose we have a variable as follows: <pre><code>let combineValues; <p dir="auto"> In such a case, the type of <code>combineValues ​​variable is of <code>any type, but as I said, <code>any is not very useful, so I want to do something like this: <pre><code>combineValues = add; <p dir="auto"> That is, put the <code>add function in <code>combineValues. As you know, in JavaScript, we can do something like this and even execute this variable as a function: <pre><code>let combineValues; combineValues = add; console.log(combineValues(8, 8)); <p dir="auto"> If we compile this code with the command <code>tsc app.ts and open the code in the browser, we will get the number <code>16. The problem is that currently the <code>combineValues ​​variable is of type <code>any so it accepts any value, even if we give it a number: <pre><code>let combineValues; combineValues = add; combineValues = 5; console.log(combineValues(8, 8)); <p dir="auto"> The code above compiles without error, but we encounter an error in the browser because we made a logical mistake. By assigning the number <code>5 to <code>combineValues, we have turned it into a normal variable that has the number <code>5 in it, and obviously such a variable cannot be implemented and we receive an error. To solve this problem, you can set the variable type to <code>function: <pre><code>let combineValues: Function; combineValues = add; combineValues = 5; console.log(combineValues(8, 8)); <p dir="auto"> By doing this in TypeScript, we immediately get an error that tells us that the number <code>5 is not a <code>function. So this solves our problem, but it is still not a perfect method because <code>Function means <i>any function! In other words, by doing this, the following code will be allowed: <pre><code>let combineValues: Function; combineValues = add; combineValues = printResult; console.log(combineValues(8, 8)); <p dir="auto"> Now, if we compile the code and open the browser, the result will be as follows: <pre><code>Result: 8 undefined <p dir="auto"> Because <code>printResult takes only one parameter, but we have set it to <code>combineValues ​​and then given two parameters to <code>combineValues! The typescript can't get any error from our code because we only set the <code>Function type for it and <code>printResult is also a function. <p dir="auto"> Our solution is function types: <pre><code>let combineValues: () => number; <p dir="auto"> As you can see, this syntax is very similar to arrow functions, but it has nothing to do with them. By putting the parenthesis sign and then the arrow sign, we say that the <code>combineValues ​​type is supposed to be a function (of course, a function that does not accept any parameters) and then we specify its output or return by adding <code>number, which here is <code>number. <p dir="auto"> Our function takes parameters, so we need to add these parameters to it: <pre><code>let combineValues: (a: number, b: number) => number; combineValues = add; combineValues = printResult; <p dir="auto"> Now I have determined that <code>combineValues ​​takes a function that has two parameters and both are <code>numbers and finally returns a <code>number. It is also not necessary that the names of these parameters are exactly the same as the main function, but anything (such as <code>a and <code>b) can be placed instead. By doing this, the second line (assignment <code>add) will be fine, but for the third line (assignment <code>printResult) we will encounter an error because our definition does not match <code>printResult (two arguments in our definition instead of one argument in <code>printResult and also return type of <code>void type in <code>printResult against number in our definition). <p dir="auto"> We can implement the same logic for <i>callback functions. For example, consider the following function: <pre><code>function addAndHandle(n1: number, n2: number, cb) { const result = n1 + n2; cb(result); } <p dir="auto"> The third parameter of this function is <code>cb or <i>callback and it is supposed to be a function that is executed inside our function and receives the <code>result value. Now, with the same logic as before, we can specify the type of callback explicitly: <pre><code>function addAndHandle(n1: number, n2: number, cb: (num: number) => void) { const result = n1 + n2; cb(result); } <p dir="auto"> That is, <code>cb requires a number as its argument and returns <code>void. why <code>void? Because I want <code>cb to execute the <code>console.log statement, so it will not have any <code>return statement. If you want <code>cb to do more things and <code>return something, you can change the above code. Now we can simply call it: <pre><code>addAndHandle(10, 20, (result) => { console.log(result); }); <p dir="auto"> As you can see, I've given it an arrow function for the third parameter (note that this is really a function and not a type - it doesn't have a colon) which <code>console.logs the value of the first two parameters. Now, if we go to the browser after compiling the code, we will see the output <code>30, which is the correct value. <p dir="auto"> Of course, the interesting point here is that if we write <code>cb with the <code>return statement, no error will be given to us: <pre><code>addAndHandle(10, 20, (result) => { console.log(result); return result; }); <p dir="auto"> We specified above that <code>cb should output <code>void, so why doesn't it give us an error for return? Because we specified <code>void in the <code>addAndHandle function, which means that we have nothing to do with the <code>cb output in the <code>addAndHandle function, so <code>void here means the output of the <code>cb function in the <code>addAndHandle function is not important to us. In simpler language, in such a case, <code>void does not say that the <code>cb function does not <code>return anything, but it says that if a value is returned, it does not matter to us (in <code>addAndHandle, of course).
Sort:  

Congratulations!


You have obtained a vote from CHESS BROTHERS PROJECT

✅ Good job. Your post has been appreciated and has received support from CHESS BROTHERS ♔ 💪


♟ We invite you to use our hashtag #chessbrothers and learn more about us.

♟♟ You can also reach us on our Discord server and promote your posts there.

♟♟♟ Consider joining our curation trail so we work as a team and you get rewards automatically.

♞♟ Check out our @chessbrotherspro account to learn about the curation process carried out daily by our team.


🏅 If you want to earn profits with your HP delegation and support our project, we invite you to join the Master Investor plan. Here you can learn how to do it.


Kindly

The CHESS BROTHERS team

Curious about HivePakistan? Join us on Discord!

Delegate your HP to the Hivepakistan account and earn 90% of curation rewards in liquid hive!

50 HP
100 HP
200 HP
500 HP (Supporter Badge)
1000 HP

Follow our Curation Trail and don't miss voting!

Additional Perks: Delegate To @ pakx For Earning $PAKX Investment Token


Curated by gwajnberg

THanks for the nice tips in typescript =)

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).


 
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 

Hello,



Thanks for your help
this Comment has been upvoted with 80%, thanks to @bgmoha who burned 800 PLANETWith this burn @bgmoha is actively participating in the CLEAN PLANET reward protocol.@bgmoha is helping @cleanplanet to grow with the curation.@cleanplanet