Understanding TypeScript Functions

10 May 2023 Balmiki Mandal 0 Typescript

Creating Functions with TypeScript

TypeScript is a powerful language that allows developers to create complex applications using object-oriented programming. One of its main features is the ability to create functions. In this article, we’ll discuss how to create functions with TypeScript.

Declaring a Function

In TypeScript, a function is declared like this:

function functionName(parameter1: dataType, parameter2: dataType): returnDataType{ 
  // Function body 
}

Where:

  • functionName is the name you give your function
  • parameter1 and parameter2 are optional parameters you can pass into the function, along with their corresponding data types
  • returnDataType is the data type of the value the function will return

Using a Function

Functions can be used in many ways. For example, you can use them to create custom calculations:

function addTwoNumbers(num1: number, num2: number): number { 
  let result = num1 + num2; 
  return result; 
} 
 
let total = addTwoNumbers(4, 5); 
console.log(total); // 9

Or you can use them to control code flow:

function checkNumber(num: number): void { 
  if (num > 10) { 
    console.log("Number is greater than 10"); 
  } else { 
    console.log("Number is less than or equal to 10"); 
  } 
} 
 
checkNumber(11); // Number is greater than 10

Conclusion

Creating and using functions with TypeScript can help you create powerful and reusable code. With the basic knowledge covered in this article, you can start experimenting and building your own functions!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.