TypeScript Function Example

Here you learn how to write function in typescript, with different return type, optional parameters, parameter with default value etc.

How to write function in typescript

Functions are basic need in any application building and functions are necessary because that make the program more readable, maintainable, and reusable code. A function is a set of statements to perform a specific task.

Like any other programming language, TypeScript also provide mechanism to write and consume function, so let's understand how to write typescript function.

Function in TypeScript

Typescript functions are very similar to JavaScript function, we can write name function and Anonymous Function

// Named function
add(x: any, y: any) {
            return x + y;
        }
// Anonymous function
result = function (x: number, y: number) { return x + y; };

We can have access modifier for function, like public | private | protected

 private getTotal(x: number, y: number): number {
            return x + y;
        }

In function definition we can set the return type, means what type of data the function will return
In above example we can see getTotal(x: number, y: number): number, number is the return type of this function.

How to call a Function in TypeScript

Remember while developing TypeScript class and any functionality in that class, where you want to consume that functionality, or where you call that function! If you want those functions to be consumed in other object / classes then you must start developing a class with export keyword .

Here is an example, we have created following class in a file called "FunctionSample.ts".

export class AccountModule {
getTotal(x: number, y: number): number {
return (x + y);
}
getGrossTotal(x: number, y: number): number {
return (x + y + 50);
}    
}

Now we see how to access functions of AccountModule class in a new class called "StudentAcct"
Now we create a new class called "Consumer.ts"

Consumer.ts
import { AccountModule } from "./FunctionSample";
let stuObj = new AccountModule();
stuObj.getGrossTotal(40, 50);
console.log(stuObj.getGrossTotal(60,80));
class StudentAcct{
showAcct() {
let acctObj = new AccountModule();
acctObj.getGrossTotal(40, 50);
    }
}

Notice, we have kept file name different than class / object name, that’s NOT good practice, but here to make you understand how to import an object from a file we have kept two name different. look at the example below.
import { ObjectName } from "./FileName";

Calling a function in typescript is same like other programming language, We just have to create a new instance of the class and the call the function.

let acctObj = new AccountModule();
acctObj.getGrossTotal(40, 50);

Using Function with parameter

In TypeScript, we can add a type annotation to each parameter of any function using a colon and the desired type, Here is an example
getGrossTotal(x: number, y: number): number {
        return (x + y + 50);
    }

in above example x is a variable and number is datatype

TypeScript Function with Optional Parameter

In typescript function we also can define optional parameter

function getfullName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}
Now to call the above function second parameter is always optional
getfullName("Akshay"); // work
getfullName("Akshay","Kumar"); // also work

So, understand the difference, optional parameter always have a “?” mark lastName?: string

Function parameter with default value

We can set default value to any parameter in typescript function

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

Now if we call the above function without second parameter, it will add the default value to output, otherwise it will show what value we pass as second parameter

getfName("Akshay"); // result: Akshay India
getfName("Akshay","Kumar"); // result: Akshay Kumar

Typescript Function return type

We can define, what data type of a function should return! here in example function returning a number.

getGrossTotal(x: number, y: number): number {
        return (x + y + 50);
    }
 
TypeScript Function
Popular Libraries
TypeScript Tutorial
TypeScript and JavaScript Examples