This will log to the console the message: The function provided returned: Hello world!
Notice how we have a function call to logReturnValueOf(...)
, and the parameter in between the (
and )
is a function expression for a function that just returns the string "Hello world!". As function parameters must specify their type, we must specify a function that takes no parameters but returns a string, which is the type () => string
. Then inside the logReturnValueOf
function, it calls its parameter with func()
, and adds the returned value to a log message.
The syntax with these uses of functions may take some time to get used to. In particular you can end up with lots of pairs of (
)
, {
and }
across different lines. However you should notice Construct's code editor, like most other coding editors, can highlight bracket pairs to help you match them up.
Returning functions
Functions can also return other functions.
You may be beginning to notice that in general, anywhere you can use a string or a number, you can also use a function. This is a useful feature of TypeScript, and is sometimes referred to as first-class functions, as functions can be treated the same as any other data type.
Here's an example of a function returning a function.
// Declare a function that returns another function
function getFunction()
{
return function()
{
console.log("Hello world!");
};
}
// Call getFunction(), which returns a function
let returnedValue = getFunction();
// Call the returned function, logging "Hello world!"
returnedValue();
Note that TypeScript again infers the return type of getFunction
from the return
statement. Since it returns a function that takes no parameters and returns nothing, its return type is () => void
. That type is then also automatically inferred for the returnedValue
variable. As you can see, quite often TypeScript is able to automatically infer and propagate types a long way through your code. In many cases, you'll only need to add type annotations to function parameters.