VOOZH about

URL: https://www.geeksforgeeks.org/typescript/how-to-write-a-function-in-typescript/

⇱ How to write a function in Typescript ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to write a function in Typescript ?

Last Updated : 23 Jul, 2025

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

Output:

15

Example 2: Add Two Numbers and Return Equivalent Hexadecimal String

Add two numbers and return equivalent hexadecimal string.

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.

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.

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.

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.

Comment
Article Tags:

Explore