TypeScript Functions

Below are different functions available in TypeScript.

  • Named Function
  • Anonymous

Named Function

// Creating the Named Function
function display()
{
    console.log("Hello World");
}

display(); // Calling the Function

Named Function with Parameter and Return Types

  • Parameters are values or arguments passed to a function.
  • Parameters can be Required, Optional, Default and Rest.
  • TypeScript compiler expects a function to receive the exact number and type of arguments as we defined in the function signature.
  • We can add types to each of the parameters and then to the function itself to add a return type.
function add(x: number, y: number): number {
    return x + y;
}
var total: number = add(10,12)
console.log(total);

Optional and Default Parameters

  • The number of arguments given to a function has to match the number of parameters the function expects
  • To make arguments as optional, add " ? " to the end of parameters we want to be optional.
  • We can set a value that a parameter will be assigned if the user does not provide one, or if the user passes undefined in its place. These are called default-initialized parameters.
  • If a default-initialized parameter comes before a required parameter, users need to explicitly pass undefined to get the default initialized value.
// firstName is Required Parameter
// lastName is Optional Parameter

function studentDetails(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}

let std1 = studentDetails("Girish");
console.log(std1);

let std2 = studentDetails("Girish","Chandra"); 
console.log(std2);

let std3 = studentDetails("Girish","Chandra","Test"); // error : Expected 1-2 arguments, but got 3.
console.log(std3);

====================================******===============================
// firstName is Required Parameter
// lastName is Default Parameter

function studentDetailsDefault(firstName: string, lastName: string = "Chandra") {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}

let std4 = studentDetailsDefault("Girish"); // works correctly , returns "Girish Chandra"
console.log(std4);

let std5 = studentDetailsDefault("Girish", undefined); // still works, returns "Girish Chandra"
console.log(std5);

let std6 = studentDetailsDefault("Girish", "Chandra", "Test");  // error : Expected 1-2 arguments, but got 3.
console.log(std6);

let std7 = studentDetailsDefault("Girish", "Chandra");  //works correctly, returns "Girish Chandra"
console.log(std7);

Rest Parameters

  • Sometimes, we want to work with multiple parameters as a group, or we may not know how many parameters a function will finally take.
  • We can gather these arguments together into a variable
  • Rest parameters are treated as a boundless number of optional parameters. When passing arguments for a rest parameter, you can use as many as you want and you can also pass none. The compiler will build an array of the arguments passed in with the name given after the ellipsis (…), allowing us to use it in our function.
function studentDetailsRest(firstName: string, ...restOfName: string[]) {
    return firstName + " " + restOfName.join(" ");
}
let std8 = studentDetailsRest("Girish", "Chandra","Test1","Test2","Test3");   
console.log(std8);

Anonymous Function

  • Anonymous function is the one which is defined as an expression.
  • Expression output is stored in a variable.
  • These functions are invoked using the variable name that the function is stored in.
// Anonymous Function

let display = function () {console.log("Hello World");};
display();

// Anonymous Functions with Parameters and Return Type

let add = function (x: number, y: number): number {
    return x + y ;
}
console.log(add(40,32));

// Anonymous Function with Required Parameter and Optional Parameter
let std1Anonymous = function (firstName: string, lastName?: string) {
    if (lastName)
    return firstName + " " + lastName;
    else
    return firstName;

}
console.log(std1Anonymous("Girish"));
console.log(std1Anonymous("Girish","Chandra"));
//console.log(std1Anonymous("Girish","Chandra","Test"));


// Anonymous Function with Required and Default Parameters

let studentDetailsDefaultAnonymous = function (firstName: string, lastName: string = "Chandra") {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}
console.log(studentDetailsDefaultAnonymous("Girish"));
console.log(studentDetailsDefaultAnonymous("Girish",undefined));
console.log(studentDetailsDefaultAnonymous("Girish","Chandra"));
//console.log(studentDetailsDefaultAnonymous("Girish","Chandra","Test"));

// Anonymous Function with Rest Parameters

let studentDetailsRestAnonymous = function (firstName: string, ...restOfName: string[]) {
    return firstName + " " + restOfName.join(" ");
}
 
console.log(studentDetailsRestAnonymous("Girish", "Chandra","Test1","Test2","Test3") );

Arrow Functions ( => )

  • Fat arrow notations (=>) are used for anonymous functions
  • In other programming languages arrow functions are also called as Lambda Functions
  • (arg1, arg2, …, argN) => expression
// Arrow Function

let dis = () => {console.log("Hello World From Arrow Function");};
dis();

// Arrow Functions with Parameters and Return Type

let addition = (x: number, y: number): number => {
    return x + y ;
};
console.log(addition(40,32));

let addition1 = (x: number, y: number): number => x + y ;
console.log(addition1(40,22));


// Arrow Function with Required Parameter and Optional Parameter
let std1Arrow = (firstName: string, lastName?: string) => {
    if (lastName)
    return firstName + " " + lastName;
    else
    return firstName;

};
console.log(std1Arrow("Girish"));
console.log(std1Arrow("Girish","Chandra"));
//console.log(std1Arrow("Girish","Chandra","Test"));


// Arrow Function with Required and Default Parameters

let studentDetailsDefaultArrow = (firstName: string, lastName: string = "Chandra") => {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
};
console.log(studentDetailsDefaultArrow("Girish"));
console.log(studentDetailsDefaultArrow("Girish",undefined));
console.log(studentDetailsDefaultArrow("Girish","Chandra"));
//console.log(studentDetailsDefaultAnonymous("Girish","Chandra","Test"));

// Arrow Function with Rest Parameters

let studentDetailsRestArrow = (firstName: string, ...restOfName: string[]) => {
    return firstName + " " + restOfName.join(" ");
};
 
console.log(studentDetailsRestArrow("Girish", "Chandra","Test1","Test2","Test3") );

// Arrow Function inside Class

class Course {
    courseCode: number;
    courseName: string;

    constructor(code: number, name: string) {
            this.courseCode = code;
            this.courseName = name;
    }

    display = () => console.log(this.courseCode +' ' + this.courseName)
}
let course = new Course(1, 'Girish Chandra');
course.display();

To execute all the above codes, save the code with filename.ts and run from command prompt as below

C:\Users\Girish\TypeScriptProj> tsc arrowfuncls.ts
C:\Users\Girish\TypeScriptProj> node arrowfuncls.js 

References

  • https://www.typescriptlang.org/docs/handbook/functions.html

Learn about more TypeScript features in our upcoming blog articles.

Happy Learning!