o7planning

TypeScript Functions Tutorial with Examples

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- What is function?

In the TypeScript programming language, a function is a named block of code. It can take parameters and return a value or nothing, and runs only when called. Functions divide a large task into small parts and perform specific operations of that program. This process increases code reusability and enhances the program's modular approach.
The syntax for declaring a regular function:

function function_name(arg1: type1, arg2: type2, argN: typeN) : return_type {
   // Statements
}
Note: Similar to JavaScript, TypeScript does not allow two functions with the same name, even if they have different parameters.

2- Regular function

The syntax for declaring a regular function:

function function_name(arg1: type1, arg2: type2, argN: typeN) : return_type {
   // Statements
}
Use the void keyword (or empty) as a return type if the function returns nothing.

function function_name(arg1: type1, arg2: type2, argN: typeN) : void {
   // Statements
}
// Same as:
function function_name(arg1: type1, arg2: type2, argN: typeN) {
   // Statements
}
Example: The minus function with two parameters of number type, and returns a value of number type.
function_ex1.ts

function minus(a: number, b: number) : number {
    return a + b;
}  
var result = minus(10, 20); // -10
console.log(`result = ${result}`);
Output:

result = -10
Example: The greeting function accepts a string parameter and returns nothing.
function_ex2.ts

function greeting(name: string) {
    var s = `Hello $name`;
    console.log(s);
}
// Call the function:
greeting('Tom'); // Hello Tom

3- Closure

In the TypeScript programming language, a Closure is a special function.
  • Similar to a function, a Closure is a block of statements with parameters and can return a value or nothing.
  • Unlike a function, a Closure has no name. However, you can identify it through a variable.
See detailed article about Closure:

4- Optional parameter

As mentioned above, TypeScript does not allow functions with the same name, but a function can include optional parameters, which must be the last parameters in the parameter list.
Syntax:
Syntax

function function_name(argM: typeM, argN: typeN, argP?:typeP, argQ?: typeQ): return_type {  
     // Statement(s)  
}
Or syntax - Optional parameter with default value:

function function_name(argM: typeM, argN: typeN,
                  argP?:typeP = defaultValueP, argQ?: typeQ = defaultValueQ): return_type {  
     // Statement(s)  
}
Example:
function_optional_args_ex1.ts

function concat(s1: string, s2: string, s3?: string): string {
    if (s3) {
        return s1 + s2 + s3;
    }
    return s1 + s2;
}
function sum(v1: number, v2: number, v3?: number, v4?: number): number {
    return v1 + v2 + (v3 ?? 0) + (v4 ?? 0);
}
function function_optional_args_ex1_test() {
    var result1 = concat('One', 'Two');
    console.log(`result1: ${result1}`);
    var result2 = concat('One', 'Two', 'Three');
    console.log(`result2: ${result2}`);

    var value1 = sum(1, 2, 3, 4);
    console.log(`value1: ${value1}`);
    var value2 = sum(1, 2, 3);
    console.log(`value2: ${value2}`);
    var value3 = sum(1, 2);
    console.log(`value3: ${value3}`);
}
function_optional_args_ex1_test(); // Call the function.
Output:

result1: OneTwo
result2: OneTwoThree
value1: 10
value2: 6
value3: 3

5- Parameters with union data type

Parameters in a function can also be declared with a union data type.
Syntax:

function function_name (
             arg1 : data_type1, arg2 : data_type2,
             arg3 : data_type31 | data_type32 | data_type3N, // Union Data Type
             arg4 : data_type4) : return_type {
    //  Statament(s)
}
Example:
function_union_type_args_ex1.ts

interface IStudent {
    studentId: number,
    studentName: string
}
interface IWorker {
    workerId: number,
    workerName: string
}
function getName(person: IStudent | IWorker): string { // Union Type Arg
    var p = person as IStudent;
    if (p.studentName) {
        return p.studentName;
    }
    return (person as IWorker).workerName;
}
function function_union_type_args_ex1_test() {
    var student = { studentId: 1, studentName: "Tom" };
    var worker = { workerId: 2, workerName: "Jerry" };

    var name1 = getName(student);
    var name2 = getName(worker);
    console.log(`name1: ${name1}`);
    console.log(`name2: ${name2}`);
}
function_union_type_args_ex1_test(); // Call the function.
Output:

name1: Tom
name2: Jerry

6- Function Overloading

As mentioned above, TypeScript does not allow functions with the same name even if they have different parameters. Function Overloading is a "circumvention" technique, which means you still have only one function with a specific name but can use it with different parameters.
The main idea for function overloading is to create a generic function that checks what type of parameter was passed when the function was called, then do some logic for the appropriate case. It is useful to add definitions for the function to help other programmers know how to use it appropriately.
Syntax:

// Definition 1
function function_name(arg_11 : type_11, arg_1N : type_1N): return_type;
// Definition 2
function function_name(arg_21 : type_21, arg_22 : type_22, arg_2M : type_2M) : return_type;
function function_name(... args : any[]) : return_type {
   // Function body.
}
Basically, there are many ways to define an overloaded function. The above syntax is recommended, which helps you to avoid the error below from the compiler:

This overload signature is not compatible with its implementation signature.
Syntax:
function_overload_ex1.ts

interface IDimension3D {
    width: number,
    height: number,
    depth: number
}
function getVolume(dimension: IDimension3D): number; // Definition 1
function getVolume(width: number): number; // Definition 2
function getVolume(width: number, height: number, depth: number): number; // Definition 3
function getVolume(...args: any[]): number {
    if (args.length == 1) {
        if (typeof args[0] == 'number') { // Use Definition 1
            return args[0] * args[0] * args[0];
        } else {  // Use Definition 2
            var dim = args[0] as IDimension3D;
            return dim.width * dim.height * dim.depth;
        }
    } else if (args.length == 3) { // Use definition 3
        return args[0] * args[1] * args[2];
    } else {
        throw Error('Argument invalid!');
    }
}
function function_overload_ex1_test() {
    var volume1 = getVolume(10); // 1000
    var volume2 = getVolume({ width: 10, height: 20, depth: 30 }); // 6000
    var volume3 = getVolume(5, 10, 15); // 750

    console.log(`volume1 = ${volume1}`);
    console.log(`volume2 = ${volume2}`);
    console.log(`volume3 = ${volume3}`);
}
function_overload_ex1_test(); // Call the function.
Output:

volume1 = 1000
volume2 = 6000
volume3 = 750
  • Interfaces
  • TypeScript instanceof
  • TypeScript typeof operator

View more Tutorials:

Maybe you are interested

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.