In this typescript example, I am going to create a callback function that will return a string depending on the text the user has entered into the second parameter of the calling function.
First of all, let us create the callback function as follows:-
function hello(text : string) : string { if (text == "Hello World!") { return "Hello Again World!" } else { return "Good Morning World!" } }
As you can see above that the call-back function will receive a string and will return another string based on the text that the user has entered.
Next, let us create the call function which will receive two parameters, the first one is the callback function and the second parameter is the text which will then become the parameter of the call-back function.
function calltheworld(callbackfunc:(text:string)=>string, message:string) { console.log(callbackfunc(message)) }
I am using the () => syntax as the function signature for the callback function which will receive one parameter of type string and return a string at the end.
Now let us enter the parameters into the calling function as follows:
calltheworld(hello, "hey")
The above line will return the following string:-
Good Morning World!
Next, let us enter another set of parameters into the above calling function again:
calltheworld(hello, "Hello World!")
This time I have entered the “Hello World!” text which will make the callback function returns the below outcome.
Hello Again World!
At last, if I entered the following parameters into the callback function then the program will not compile due to the safeguarding protocal which will activate because the first parameter of the calling function which is a string will not match the signature of the first parameter which is a callback function which accepts a string as its parameter and returned another string at the end.
calltheworld("hey", "he")
The parameter with a signature is a strong type parameter that will not allow the user to misenter any other parameter than the one specified by its parameter signature.