Open In App

How to write a function in Typescript ?

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Writing a function in TypeScript is similar to writing it 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: Adding Two Numbers

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

TypeScript
// 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

Add two numbers and return equivalent hexadecimal string.

TypeScript
// 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: Good Morning Message with Optional Name

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

TypeScript
// 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: Exponentiation with Default Power

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

TypeScript
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

Example 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.
 

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

console.log(sum(1, 2, 3, 4, 5));
console.log(sum(10, 20)); 
console.log(sum(100));
console.log(sum()); 

Output

15
30
100
0

Adding type annotations to TypeScript functions enhances readability, maintainability, and type safety, ensuring correct usage and catching errors at compile time. This includes optional, default, and rest parameters, making functions more robust and versatile compared to standard JavaScript functions.



Next Article

Similar Reads