In TypeScript, you can define a function using the ‘function‘ keyword followed by the function name, parameters in parentheses, and a return type after a colon. The function body is enclosed in curly braces ‘‘.
Here’s an example of a function definition in TypeScript:
function add(a: number, b: number): number {
return a + b;
}
In this example, we’ve defined a function called ‘add‘ which takes two parameters ‘a‘ and ‘b‘ of type ‘number‘ and returns a value of type ‘number‘.
To call a function in TypeScript, you use the function name followed by the arguments within parentheses. Here’s how you can call the ‘add‘ function:
const result = add(3, 4);
console.log(result); // Output: 7
This function call passes ‘3‘ and ‘4‘ as arguments to the ‘add‘ function and stores the return value in the ‘result‘ variable.
Here’s a complete example in TypeScript:
function add(a: number, b: number): number {
return a + b;
}
const result = add(3, 4);
console.log(result); // Output: 7
The function definition and call is represented as follows:
Function Definition:
$$\text{function add}(a: \mathbb{N}, b: \mathbb{N}): \mathbb{N} \\
\{ \\
\quad \text{return } a + b; \\
\}$$
Function Call:
const result = add(3, 4);