What are TypeScript functions? Definition, type safety and use

With TypeScript, users can declare types for functions, parameters and return values. Since TypeScript checks whether the correct data types are used, declaring types helps to detect errors earlier on and increases code quality.

What are TypeScript functions?

TypeScript functions are a central component of TypeScript. Functions in TypeScript are similar to those in JavaScript but have the additional advantage of static typing. With this approach, data types for variables, parameters and return values are already defined at compile time and cannot be changed during execution. This reduces errors in the production environment.

Another feature of TypeScript functions is their flexibility. Functions can have optional and default values for parameters, which makes it easier to customize them for different use cases. Possible uses include data processing, user interface interactions, asynchronous programming and much more. You can also define overloads to provide different functionalities based on the input values.

In addition to declaring functions, you can also use auxiliary functions in TypeScript. These functions are a shorter notation and are often used in modern JavaScript development practices.

TypeScript functions are key to increasing the security and readability of code used in TypeScript projects. At the same time, their flexibility and adaptability makes them suitable for a wide range of requirements.

What is the syntax for TypeScript functions?

TypeScript is a superset language of JavaScript. As such, the syntax of TypeScript functions is similar to that of JavaScript functions. The function code follows in curly brackets { }. This is where the actual logic of the function is implemented. Here is the basic syntax of a TypeScript function:

function functionName(parameter1: type, parameter2: type): returnType {
    // Function Code
    return result; // (optional)
}
typescript
  • function: this keyword marks the beginning of the function declaration.
  • functionName: this is the name of the function. You should choose a descriptive name that reflects the function’s task.
  • parameter1, parameter2: these are the parameters that the function expects. Each parameter is identified by its name and the expected data type (type annotation).
  • returnType: this is the data type that the function returns. You can also specify void if the function does not return a value.
  • return result is optional and is used if the function should return a value.

TypeScript functions are called by using the function name followed by parentheses. In the parentheses, you specify the arguments (input values) for the function if it expects parameters.

functionName(argument1, argument2, ...);
typescript
Cheap domain names – buy yours now
  • Free website protection with SSL Wildcard included
  • Free private registration for greater privacy
  • Free 2 GB email account

TypeScript function examples

TypeScript functions are extremely versatile and can be used to perform calculations, operations and complex processes in applications.

Anonymous functions

Anonymous functions in TypeScript are functions that do not have a name and are passed directly in expressions or as arguments to other functions. Anonymous functions are beneficial if you only need a function in one place of the code and do not want to assign your own function name.

var greet = function(name) {
    return "Hello, " + name + "!";
};
var message = greet("John");
console.log(message); // Output: "Hello, John!"
typescript

In this example, the anonymous function is stored in the variable greet and called later to create a personalized greeting message for John.

Anonymous functions also include lambda functions, which are known as arrow functions.

const add = (a: number, b: number) => a + b;
const result = add(3, 5); // Output: 8
typescript

Here, an anonymous function that adds two numbers is assigned to the variable add and then called.

Default parameters

Default parameters (also known as standard parameters) in TypeScript allow you to define TypeScript functions so that they have default values for parameters. When the function is called and no value is passed as a parameter, the default value is used instead.

function greet(name: string = "World") {
    return "Hello, " + name + "!";
}
console.log(greet()); // Output: "Hello, World!"
console.log(greet("John")); // Output: "Hello, John!"
typescript

Here, the greet function has the default value world for the name parameter. If no value is passed for name when the function is called, the default value will be used automatically.

Rest parameters

With rest parameters (also known as rest operators or rest parameter syntax) in TypeScript, you can collect an unspecified number of arguments as TypeScript arrays in a function. This is useful if you want to write functions that can process varying amounts of arguments.

function sum(...numbers: number[]): number {
    let total = 0;
    for (const num of numbers) {
        total += num;
    }
    return total;
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
typescript

In the example, the sum function collects any amount of number as the rest parameter numbers and adds them together to calculate the total sum. You can pass as many numbers as you like, and the function will add them all up.

Overloading

Function overloading is used to define multiple function declarations with the same names but different parameter or return types. This helps TypeScript to automatically select the correct function declaration depending on the arguments passed and to perform type checks.

function concatenate(a: string, b: string): string;
function concatenate(a: number, b: number): string;
function concatenate(a: any, b: any): string {
    return a.toString() + b.toString();
}
console.log(concatenate("Hello, ", "World")); // Output: "Hello, World"
console.log(concatenate(3, 5)); // Output: "35"
typescript

In the example above, we have two function overloads for concatenate. The first accepts two strings and the second accepts two numbers. The function itself converts the passed arguments to strings and concatenates them. TypeScript automatically selects the appropriate overload based on the arguments passed and performs the necessary type checks.

Function overloads are particularly useful if you are developing an API or library where you want to ensure that the use of the function is simple and error-free, regardless of the different types of parameters provided by the users.

Was this article helpful?
Page top