How to write a function in Typescript ?

Writing a function in TypeScript is similar to writing them in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.

Syntax: Let’s see a basic TypeScript function syntax (with two arguments)

function functionName(arg1: <arg1Type>, 
arg2: <arg2Type>): <returnType> {
// Function body...
}

Below are some functions to help better understand.

Example 1: In this example, we are writing a function to add two numbers
 

Javascript
// TypeScript Code
// Following function returns the addition
// of it's two parameters
function addTwo(a: number, b: number): number {
    return a + b;
}

console.log(addTwo(7, 8)); // logs 15

Output:

15

Example 2: Add two numbers and return equivalent hexadecimal string.

Javascript
// Following function adds it's two parameters then
// returns it as string form in base 16
function getHexAddition(a: number, b: number): string {
    return (a + b).toString(16);
}

console.log(getHexAddition(10, 16)); // logs '1a'

Output:

1a

Adding Optional and Default Parameters: Adding an optional parameter is super simple, just add ? to the end of the argument name.  

Example 3: Write a function that logs a Good Morning message with a name, if a name is not passed then logs only Good Morning.

Javascript
// Following function returns good morning
// message based on value of name passed
function goodMorning(name?: string): string {
   
    // if name exits use it as suffix else ignore name
    const suffix = (name ? `, ${name}.` : '.');
    return 'Good Morning' + suffix;
}

// logs 'Good Morning.'
console.log(goodMorning());

// logs 'Good Morning, Sam.'
console.log(goodMorning('Sam')); 

Output: For default argument suffix it with an equal sign and default value (TS compiler will automatically deduce the type for default argument based on provided value).

Good Morning.
Good Morning, Sam.

Example 4: Write a function that returns the base^{power}, if power is not provided then it is assumed to be 1.

Javascript
function pow(base: number, power = 1): number {
   return Math.pow(base, power);
}

console.log(pow(7));    // logs 7
console.log(pow(7, 2)); // logs 49

Output:

7
49

Approach 5: Function with Rest Parameters

In TypeScript, you can define functions with rest parameters, which allow you to accept an indefinite number of arguments as an array. Rest parameters are denoted by three dots (…) followed by the parameter name. Rest parameters must be of an array type.
 

JavaScript
function sum(...nums: number[]): number {
    return nums.reduce((acc, val) => acc + val, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // Logs 15 (1 + 2 + 3 + 4 + 5)
console.log(sum(10, 20));        // Logs 30 (10 + 20)
console.log(sum(100));           // Logs 100 (single argument)
console.log(sum());              // Logs 0 (no arguments)

Output

15
30
100
0