• TypeScript Tutorial

  • TypeScript Control Structures

  • TypeScript Function Types

  • TypScript Classes

Functions in TypeScript

What is a TypeScript Function?

A function in TypeScript is a reusable block of code designed to perform a specific task. TypeScript functions are strongly typed, meaning you can define the types of parameters and the return value, ensuring better reliability and fewer runtime errors.

Functions help in organizing code, reducing repetition, and making the program more manageable.

Example:
Suppose a shopping cart application where a function calculates the total cost of items. This function can be reused whenever the cart is updated, saving time and effort.

tsx
1function calculateTotal(price: number, quantity: number): number {
2  return price * quantity;
3}
4console.log(calculateTotal(100, 3)); // Output: 300

Syntax of TypeScript Function

A TypeScript function is defined using the function keyword, followed by the function name, parameters (with types), and a return type.

tsx
1function functionName(param1: type, param2: type): returnType {
2  // Function body
3}

Function Types in TypeScript

TypeScript allows defining the types of both parameters and the return value. This ensures that functions are predictable and safe to use.

  • Parameter Types: Define the expected types of inputs.
  • Return Type: Specify the type of value the function will return.
  • Void: Used when the function does not return any value.

Parameter Type

Parameter types ensure that the function receives inputs of the correct type, preventing unintended data from causing errors. This is particularly useful when working with mathematical calculations or processing user inputs. For instance, a function handling only number inputs guarantees proper arithmetic operations.
Example:

tsx
1function add(a: number, b: number): number {
2  return a + b;
3}
4console.log(add(5, 10)); // Output: 15

Here, both a and b are of type number, and the function ensures only numbers are passed.

Return Type

Defining a return type ensures that the output of a function matches the expected type. It helps in maintaining consistency and avoiding unexpected values in scenarios like returning results of calculations, formatted strings, or API responses. This is useful for applications that rely on predictable outputs, such as payment processing systems or data analysis tools.
Example:

tsx
1function multiply(a: number, b: number): number {
2  return a * b;
3}

This function ensures that the returned value is always a number.

Void Return Type

The void return type is used for functions that perform actions without returning a value, such as logging, sending notifications, or updating a UI element. For example, a logError() function might write an error message to a log file without needing to return any value. This type signals that the function’s purpose is an action, not a computation.
Example:

tsx
1function logMessage(message: string): void {
2  console.log(message);
3}

Optional Parameters

Optional parameters are used when some arguments might not always be necessary for a function to execute. For instance, in a greeting function, the user’s age might be optional:
greet("Alice") works fine even if age is not provided. This is helpful in cases where additional details enhance functionality but are not critical to the operation.
Example:

tsx
1function greet(name: string, age?: number): string {
2  return age ? `Hello, ${name}. You are ${age} years old.` : `Hello, ${name}.`;
3}
4console.log(greet("Alice")); // Output: Hello, Alice.

Default Parameters

Default parameters ensure that functions work even when specific arguments are not provided. For example, in a tax calculator, a default tax rate can be used if the user does not specify one.
Example:

tsx
1function calculateDiscount(price: number, discount: number = 10): number {
2  return price - (price * discount) / 100;
3}
4console.log(calculateDiscount(100)); // Output: 90

Named Parameters

Named parameters allow passing arguments as an object, improving readability and reducing the risk of mixing up argument order. For example, in a createUser() function, createUser({ name: "Alice", age: 30 }) is clearer than createUser("Alice", 30). This is especially useful in functions with multiple parameters where order might be confusing.
Example:

tsx
1function createUser({ name, age }: { name: string; age: number }): string {
2  return `User ${name} is ${age} years old.`;
3}
4console.log(createUser({ name: "John", age: 30 })); // Output: User John is 30 years old.

Type Alias

Type aliases are used to define reusable custom types, making the code modular and easier to maintain. For example, creating a User type for user-related data allows you to use the same type across multiple functions, ensuring consistency. This is ideal for large applications where types are repeated in different contexts, such as defining entities in a database.
Example:

tsx
1type User = { name: string; age: number };
2function displayUser(user: User): string {
3  return `${user.name} is ${user.age} years old.`;
4}

Anonymous Function

Anonymous functions are used for one-time operations, such as event handling or passing as arguments to higher-order functions.
Example:

tsx
1let sum = (a: number, b: number): number => {
2  return a + b;
3};
4console.log(sum(5, 10)); // Output: 15

Frequently Asked Questions