With TypeScript, users can declare types for functions, para­met­ers 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 JavaS­cript but have the ad­di­tion­al advantage of static typing. With this approach, data types for variables, para­met­ers and return values are already defined at compile time and cannot be changed during execution. This reduces errors in the pro­duc­tion en­vir­on­ment.

Another feature of TypeScript functions is their flex­ib­il­ity. Functions can have optional and default values for para­met­ers, which makes it easier to customize them for different use cases. Possible uses include data pro­cessing, user interface in­ter­ac­tions, asyn­chron­ous pro­gram­ming and much more. You can also define overloads to provide different func­tion­al­it­ies 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 JavaS­cript de­vel­op­ment practices.

TypeScript functions are key to in­creas­ing the security and read­ab­il­ity of code used in TypeScript projects. At the same time, their flex­ib­il­ity and ad­apt­ab­il­ity makes them suitable for a wide range of re­quire­ments.

What is the syntax for TypeScript functions?

TypeScript is a superset language of JavaS­cript. As such, the syntax of TypeScript functions is similar to that of JavaS­cript functions. The function code follows in curly brackets { }. This is where the actual logic of the function is im­ple­men­ted. 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 de­clar­a­tion.
  • func­tion­Name: this is the name of the function. You should choose a de­script­ive name that reflects the function’s task.
  • parameter1, parameter2: these are the para­met­ers that the function expects. Each parameter is iden­ti­fied by its name and the expected data type (type an­nota­tion).
  • re­turn­Type: 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 par­en­theses. In the par­en­theses, you specify the arguments (input values) for the function if it expects para­met­ers.

functionName(argument1, argument2, ...);
typescript
Cheap domain names – buy yours now
  • Free website pro­tec­tion with SSL Wildcard included
  • Free private re­gis­tra­tion for greater privacy
  • Free Domain Connect for easy DNS setup

TypeScript function examples

TypeScript functions are extremely versatile and can be used to perform cal­cu­la­tions, op­er­a­tions and complex processes in ap­plic­a­tions.

Anonymous functions

Anonymous functions in TypeScript are functions that do not have a name and are passed directly in ex­pres­sions or as arguments to other functions. Anonymous functions are be­ne­fi­cial 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 per­son­al­ized 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 para­met­ers

Default para­met­ers (also known as standard para­met­ers) in TypeScript allow you to define TypeScript functions so that they have default values for para­met­ers. 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 auto­mat­ic­ally.

Rest para­met­ers

With rest para­met­ers (also known as rest operators or rest parameter syntax) in TypeScript, you can collect an un­spe­cified 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.

Over­load­ing

Function over­load­ing is used to define multiple function de­clar­a­tions with the same names but different parameter or return types. This helps TypeScript to auto­mat­ic­ally select the correct function de­clar­a­tion 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 con­cat­en­ates them. TypeScript auto­mat­ic­ally selects the ap­pro­pri­ate overload based on the arguments passed and performs the necessary type checks.

Function overloads are par­tic­u­larly useful if you are de­vel­op­ing an API or library where you want to ensure that the use of the function is simple and error-free, re­gard­less of the different types of para­met­ers provided by the users. 133e3bd4651a9100beeedd44acb6f1b4

4823016084ab8c27d0450cc1273217d7

ebbb996ca0c42db05ec8d690c6274b4e

04954b418af6a01dc13e9a2176478907

705341800163cbdf9246e52b056e2666

Go to Main Menu