![]() |
VOOZH | about |
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.
In this example, we are writing a function to add two numbers
Output:
15Add two numbers and return equivalent hexadecimal string.
Output:
1aAdding Optional and Default Parameters: Adding an optional parameter is super simple, just add ? to the end of the argument 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.Write a function that returns the base^{power}, if power is not provided then it is assumed to be 1.
Output:
7
49In 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
0Adding 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.