TypeScript functions

Key takeaways:

  • TypeScript functions enhance JavaScript functions with static typing.

  • Functions can be declared using the function keyword, as function expressions, or as arrow functions.

  • TypeScript supports optional parameters, default parameters, and rest parameters.

  • Function overloading allows a single function to have multiple signatures.

  • Best practices include using type annotations, aiming for functional purity, and avoiding overuse of the any type.

In the world of programming, functions serve as the building blocks of software development. They provide reusable blocks of code, making programs more modular, readable, and maintainable. TypeScript enhances the functionality of traditional JavaScript by adding static typing, among other features. With TypeScript, functions become even more powerful, providing developers with additional tools to write robust and scalable code.

How to declare a TypeScript function

In TypeScript, we can declare a function using the function keyword. We can also define a function as a function expression and an arrow functionArrow functions, introduced in ECMAScript 6 (ES6), provide a concise syntax for writing functions, especially for short anonymous functions.. Here are the examples of both methods:

// Function declaration
function functionName(argument1: <argument1Type>,
argument2: <argument2Type>, ...): <returnType> {
// Function statements ...
}
// Function expression
const functionName = function(argument1: <argument1Type>,
argument2: <argument2Type>, ...): <returnType> {
// Function statements ...
};
// Arrow function
const functionName = (argument1: <argument1Type>, ...): <returnType> => /* Function statement */ ;

In the above syntax:

  • functionName is the name of the function.

  • argument1 and argument2 are the function parameters, we can add comma-separated multiple parameters.

  • <argument1Type> and <argument2Type> are the types of function parameters.

  • <returnType> is the type of value returned by the function.

Defining the sum() function in TypeScript

Let’s implement the function to add two numbers with the all above-mentioned methods:

// Function declaration
function sum(x: number, y: number): number {
return x + y;
}
console.log("1 + 2:", sum(1, 2)); // Output: 1 + 2: 3
// Function expression
const add = function(x: number, y: number): number {
return x + y;
};
console.log("3 + 4:", add(3, 4)); // Output: 3 + 4: 7
// Arrow function
const total = (x: number, y: number): number => x + y;
console.log("5 + 6:", total(5, 6)); // Output: 5 + 6: 11

In the above code:

  • Lines 2–5: We declare the sum() function that takes two parameters x and y, both of which are of type number and return a value of type number. Inside this function, we return the sum of x and y. We call the sum() function and log the output on the console.

  • Lines 8–11: We define a function expression to add two values and assign to a variable add. This function takes two parameters x and y, both of type number, and returns their sum. We call the add() function and log the output on the console.

  • Lines 14–15: We define an arrow function named total. It takes two parameters x and y, both of type number, and returns their sum. We call the total() function and log the output on the console.

Types of a function parameter

TypeScript provides various ways to define parameter types: optional, default, and rest parameters. Let’s discuss them one by one.

Optional parameters in a TypeScript function

Optional parameters allow for flexibility in function calls by making certain parameters not required. These parameters are marked with a ? symbol after their name in the function declaration. Let’s see this in the example below:

// Optional parameter
function printMessage(message: string, urgency?: boolean): void {
if (urgency) {
console.log(`URGENT: ${message}`);
} else {
console.log(message);
}
}
printMessage("Hello"); // Output: Hello
printMessage("Meeting soon!", true); // Output: URGENT: Meeting soon!

In the above code:

  • Lines 2–8: We declare the printMessage() function that takes two parameters: message, which is of type string, and urgency, which is an optional parameter (?:) of type boolean. The return type of this function is specified as void, meaning it doesn’t return any value. Inside this function:

    • Lines 3–4: We use the if condition to check if the urgency parameter is true. If urgency has been provided and evaluated to true, it logs the message prepended with "URGENT:".

    • Lines 5–7: We use the else case to implement the otherwise case in which we simply log the message without any prefix.

  • Line 10: We call the printMessage() function with only one argument, "Hello". Since the urgency parameter is optional, so it’s not necessary to provide it. We can see the output is Hello.

  • Line 11: We call the printMessage() function with two arguments: "Meeting soon!" for the message parameter and true for the urgency parameter. Since urgency is true, we can see the output is URGENT: Meeting soon!.

Default parameters in a TypeScript function

Default parameters provide the default values for parameters if no argument is provided during the function call. They are specified in the function declaration itself. Let’s see it in the example below:

// Default parameter
function greet(name: string, greeting: string = "Hello"): void {
console.log(`${greeting}, ${name}!`);
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob", "Hi there"); // Output: Hi there, Bob!

In the above code:

  • Lines 2–4: We declare the greet() function that takes two parameters: name of type string, and greeting is a default parameter initialized to "Hello". If no value is provided for greeting during the function call, it defaults to "Hello". The return type of this function is specified as void, meaning it doesn’t return any value. Inside this function, we log the greeting with the name.

  • Line 6: We call the greet() function with only one argument, "Alice". Since no value is provided for the greeting parameter, it defaults to "Hello". We can see the output string is Hello, Alice!.

  • Line 7: We call the greet() function with two arguments: "Bob" for the name parameter and "Hi there" for the greeting parameter. Since a value is provided for the greeting parameter, it overrides the default value. We can see the output string is Hi there, Bob!.

Rest parameters in a TypeScript function

Rest parameters allow functions to accept an indefinite number of arguments as an array. These parameters are denoted by three dots (...) followed by the parameter name, and they must be the last parameter in the function parameter list. Let’s see an example of it below:

// Rest parameters
function sum(...numbers: number[]): number {
let total = 0;
for (let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total;
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(5, 10, 15, 20)); // Output: 50

In the above code:

  • Lines 2–4: We declare the sum() function that takes any number of arguments of type number. The rest parameter syntax ...numbers: number[] allows us to capture all the arguments passed to the function and store them in an array named numbers. Inside this function, we use the for loop to calculate the sum of the numbers array in a total variable. Lastly, we return the total.

  • Line 10: We call the sum() function with three arguments: 1, 2, and 3. Since sum accepts any number of arguments, all provided arguments are captured by the rest parameter ...numbers and stored in an array. The function then sums up these numbers and returns the result. We log the result on console.

  • Line 11: Similarly, we call the sum() function with four arguments: 5, 10, 15, and 20. Again, all arguments are captured by the rest parameter and summed up. We log the result on the console.

Function overloading in TypeScript

TypeScript supports function overloading, which allows a single function to have multiple signatures. This is useful when a function can accept different combinations of argument types. Let’s see an example of function overloading in the following playground:

// Function overloading
function formatInput(input: string): string;
function formatInput(input: number, decimal: number): string;
function formatInput(input: string | number, decimal: number = 0): string {
if (typeof input === "string") {
return input.toUpperCase();
} else {
return input.toFixed(decimal);
}
}
console.log(formatInput("hello")); // Output: HELLO
console.log(formatInput(3.14159, 2)); // Output: 3.14

In the above code:

  • Lines 2–3: We declare two overloaded versions of the formatInput() function. The first overload expects a single parameter of the type string, and the second overload expects two parameters: input and decimal, both of type number.

  • Lines 4–10: We declare the actual implementation of the formatInput() function. It takes two parameters: input, which can be either of type string or number, and decimal, which is optional and defaults to 0. The return type of the function is string. Inside this function:

    • Lines 5–6: We use the if statement to check the type of the input parameter. If the input is of type string, it converts it to uppercase using the toUpperCase() method and return.

    • Lines 7–9: We use the else case to implement the otherwise case in which we format the input to a string with a fixed number of decimal places using the toFixed() method, with the number of decimal places specified by the decimal parameter.

  • Line 12: We call the formatInput() function with a single argument "hello", which matches the first overload. Since the argument is a string, it returns the string converted to uppercase. We can see the output string is HELLO.

  • Line 13: We call the formatInput() function with two arguments 3.14159 and 2, which matches the second overload. Since the first argument is a number, it formats the input to a string with two decimal places. We can see the output string is 3.14.

Note: If you’re interested in improving your TypeScript, including learning more about functions and other advanced topics, enroll our "Unleashing the Power of TypeScript" course. You’ll learn about reducers, generics, context API, and polymorphic components. This course will also drive you through the major features of TypeScript 5.0.

Best practices

Here are some of the best practices for using TypeScript functions:

  • Type annotations: Always specify parameter and return types to enhance code clarity and maintainability.

  • Functional purity: Aim for pure functions that don’t modify external state and always return the same output for the same input.

  • Use arrow functions sparingly: While arrow functions can improve readability, avoid overusing them, especially for complex logic.

  • Avoid any type: Minimize the usage of the any type as it bypasses TypeScript's type checking.

Conclusion

TypeScript offers a means to encapsulate reusable blocks of code, thus promoting modularity, readability, and maintainability in software projects. Understanding the syntax for declaring functions is crucial for leveraging their full potential. It facilitates the definition of various types of function parameters, including optional, default, and rest parameters. Function overloading enables the declaration of multiple function signatures within a single function definition. Best practices are essential for writing clean and maintainable code. These features enhance the flexibility and expressiveness of functions, allowing developers to design interfaces that accommodate diverse use cases and input scenarios seamlessly.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What are the functions in TypeScript?

Functions in TypeScript are blocks of reusable code that can accept parameters and return values. They are similar to JavaScript functions but with added type annotations. TypeScript functions can be:

  • Named functions: These are defined using the function keyword and have a specific name.
function add(x: number, y: number): number {
    return x + y;
}
  • Function expressions: These assign a function to a variable, allowing for flexible function creation and passing.
const add = function(x: number, y: number): number {
    return x + y;
};
  • Arrow functions: These provide a concise syntax for writing function expressions, often used for short, simple functions.
const add = (x: number, y: number): number => x + y;

TypeScript functions can have optional parameters, default parameters, and rest parameters, and support function overloading.


What is some function in TypeScript?

The question might be referring to the some() array method, which is also available in TypeScript. The some() function tests whether at least one element in the array passes the test implemented by the provided function. Here’s an example:

function hasEvenNumber(numbers: number[]): boolean {
    return numbers.some((num: number) => num % 2 === 0);
}

console.log(hasEvenNumber([1, 3, 5, 7])); // false
console.log(hasEvenNumber([1, 2, 3, 4])); // true

Does TypeScript have a main function?

TypeScript doesn’t have a built-in main() function like some other programming languages. However, we can create the main() function as an entry point for our program:

function main() {
    console.log("This is the main function");
    // Program logic here
}

// Call the main function to start the program
main();

This approach is optional, and we can structure the TypeScript program without a specific main() function.


What is a generic function in TypeScript?

A generic function in TypeScript is a function that can work with multiple types while maintaining type safety. It uses type parameters, usually denoted by <T>, to create reusable components. Here’s an example:

function identity<T>(arg: T): T {
    return arg;
}

let output1 = identity<string>("myString");
let output2 = identity<number>(100);

In this example, the identity function can work with any type. The type T is determined when the function is called, allowing for flexible and type-safe usage.

Generic functions are particularly useful when we want to create functions that can handle different types without losing type information, making the code more reusable and maintainable.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved