TypeScript functions are fundamental building blocks of TypeScript. They describe how to do things, In this tutorial, we will learn how to create functions in TypeScript, how to annotate the Parameter and return type with type information, etc.
Table of Contents
What is a Function?
A TypeScript function is a block of code that performs a specific task or calculates a value. We may pass values to the function and it may return a value. We define the function only once in our program, but execute or invoke it many times i.e. we reuse it in other parts of the program. Functions also make code readable & maintainable.
Creating a function
The simple way to create a function (or define a function) is to use the function declaration or function statement.
A function declaration starts with a function keyword. It is followed by a list of parameters and then followed by statements inside curly braces {…}
Function Declaration Syntax
The Syntax for creating a function is as follows
1 2 3 4 5 | function name(param1[:type], param2[:type], param3[:type]) [:returnType] { [statements] } |
Name
: The function name. It uniquely identifies the function and is required. We use the name to refer to the function elsewhere in the application. The JavaScript behind the scene creates a variable and assigns the function to it. A function name must follow all the rules of variable naming. Hence we can use only letters, digits, underscores, and dollar signs.
param
contains the list of parameters (comma-separated) inside parentheses. They are optional. Functions can have multiple parameters or no parameters at all.
type
is the Data Type of the parameter. The type is optional. If we do not specify any type then the TypeScript assumes the type as any
returnType
is the Data Type of value returned by the function.
statements
comprise the body of the function. It will contain zero or more statements inside curly braces {…}. These statements are executed when the function is invoked. The function body must be always enclosed in curly braces even if it consists of a single statement or no statement at all.
Function example
The following is an example of a TypeScript function.
We name the function as calcArea
. It takes two parameters width
& height
. The data type of both the parameters is number.
Inside the function body, we declare the result variable and assign the multiplication of width
& height
to it.
The return statement specifies the value that the function returns. In the example, we return the result
, which contains the multiplication of width
& height
.
1 2 3 4 5 6 | function calcArea(width:number, height:number):number { let result= width * height; return result; } |
You can also return the result of an expression directly.
1 2 3 4 5 | function calcArea(width:number, height:number):number { return width * height; } |
Calling a Function
Functions are useful only if it executes the statements present in their body. Defining or declaring a function does not execute it. We need to invoke or call or execute it.
We invoke the function, by using the function name followed by the value for each parameter inside the parentheses.
In the following example, we invoke the calcArea
function. We pass values to the width
& height
parameters inside the parenthesis. We store the return value in a variable area
and print it in the console.
1 2 3 4 5 6 7 8 9 10 11 | function calcArea(width:number, height:number):number { return width * height; } let area=calcArea(10,5) console.log(area) //50 area=calcArea(50,50) console.log(area) //2500 |
Passing Value to a function
The Functions can accept values from the calling program. To do that functions must declare what values it needs in their definition. We call them parameters.
The calling program can pass value to those parameters when invoking the function. We call them arguments.
The following code, calcArea
declares two parameters, i.e. width & height. When we call the function calcArea
with 10 & 5 as the value to it. 10 & 5 are arguments to the function calcArea
1 2 3 4 5 6 7 8 | function calcArea(width:number, height:number):number { return width * height; } let area=calcArea(10,5) console.log(area) //50 |
TypeScript compiler throws an error if you pass more or fewer arguments than those declared by the function. You can handle fewer arguments by using the Optional Parameters and more arguments by using the Rest Parameters.
JavaScript functions can accept more (or fewer) arguments than those declared in the function declaration. It will not throw any errors. If you pass fewer arguments, then the parameter that does not receive value is initialized as undefined. If you pass excess arguments, those can be accessed either using the arguments object in JavaScript or using the Rest Parameters in JavaScript.
Returning a value from a Function
A TypeScript function may or may not produce a value. When it does, we use the return statement to return the value to the calling program.
A return statement consists of a return keyword followed by the value that we want the function to return. The return statement also terminates the function and control is returned to the calling program.
We use the assignment operator to capture the returned value and assign it to a variable.
The following example calculates the power of a number. We capture the returned value in a variable result
and print it to the console.
1 2 3 4 5 6 7 8 9 10 11 12 13 | function power(base:number, exponent:number):number { let result = 1; for (let count = 0; count < exponent; count++) { result *= base; } return result; //returning the result }; //Use assignment operator to capture the returned value let result = power(10,2) console.log(result) //100 |
Returning Void
The Typescript infers void as the return type for a function that doesn’t return a value or a return statement that does not return anything. The return value of such a function is undefined.
1 2 3 4 5 6 7 8 | function sayHello() { console.log("Hello") } let result=sayHello() //Data Type of result is void console.log(result) //undefined |
Function with a return statement, but without an expression after it will also return void.
1 2 3 4 5 6 7 8 9 | function sayHello() { console.log("Hello") return } let result=sayHello() console.log(result) //undefined |
You can include any complex expressions in the return statement.
1 2 3 4 5 6 7 8 | function addNum(a:number,b:number) { return a+b } let result=addNum(1,2) //result is number console.log(result) //3 |
Functions that Never Return
A function may not return at all. The functions with an infinite loop or function that throws an error are examples of such functions.
TypeScript infers the return type as never.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //Infinite loop // Inferred return type: never var x = function infiniteLoop() { while (true) { } } // Always throws an error // Inferred return type: never var y=function throwError() { throw new Error("Some errors occurred"); } |
Functions & Variable Scope
The variables have a scope or visibility. The scope of a variable determines which part of the program can access it
Local Variables
A function can define a variable within its body. They become part of the function Scope. We can access that variable only within that function and not outside of it.
1 2 3 4 5 6 7 8 9 10 | function sayHello() { let message = "Hello"; //This variable can be accessed only withing this function alert(message); } sayHello(); alert(message); //Uncaught ReferenceError: message is not defined |
Outer Variables
While we can access the variable defined outside the function.
1 2 3 4 5 6 7 8 9 10 11 12 | let message = "Hello"; //This variable is defined outside and can be accessed by the function function sayHello() { alert(message); //Hello message="Hello Again" } sayHello(); alert(message); //Hello Again |
In this example, we create the variable message
inside the function. It will override the variable present outside the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | let message = "Hello"; function sayHello() { //declare a message inside the function. let message="Hello from function" alert(message); //"Hello from function" } sayHello(); alert(message); //Hello No change here |
Functions are objects
Functions are objects in TypeScript. Functions are a special type of object that also has a code. We can execute that code whenever we want. To execute all we need to use the () Operator after the function name. Inside the ()
we can pass a value for each parameter.
The function name without the ()
refers to the function object.
For example, sayHello
(without ()
) in the following code refers to the function object. To Execute the function we need to use the parentheses sayHello()
.
1 2 3 4 5 | function sayHello() { console.log("Hello") } |
We can attach a property to functions
Since functions are objects, we can attach properties and methods to them. In the following example, we are adding a property c
to the function addNum
. You can refer to that property using the addNum.c
1 2 3 4 5 6 7 8 9 10 11 | function addNum(a:number, b:number) { console.log(addNum.c) return a + b + addNum.c } addNum.c = 100 let result = addNum(1, 2) console.log(result) //103 |
We can store functions in a variable
We can store functions in a variable, object, or array. The following example creates addNum
function and stores it in test
variable. Now we can invoke the function using test()
also.
1 2 3 4 5 6 7 8 9 10 | function addNum(a:number,b:number) { return a+b } let test = addNum let result = test(1,2) console.log(result) //3 |
We can read the function just like any other variable. The following code uses the alert function to display the contents of the addNum
. You will see the code of the function displayed on your screen.
1 2 3 4 5 6 7 | function addNum(a:number, b:number) { return a + b } alert(addNum) |
Since alert is also a function, just check to see if you can see its code.
1 2 3 | alert(alert) |
You will see the message native code. That is because the alert is part of the JavaScript code and is included as binary. Since there is no point in showing the binary code, it will display the message native code.
Pass functions as arguments to another function
Since functions are variables, we can pass them as an argument to another function. You can also return a function from a function.
In the following example, we create two functions addNum
& multiplyNum
. The third function operate
takes func
as the first argument, where it expects us to pass a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function addNum(a:number, b:number) { return a + b } function multiplyNum(a:number, b:number) { return a * b } function operate(func:any, a:number, b:number):number { return func(a, b) } let result = operate(addNum, 10, 10) console.log(result); //20 result = operate(multiplyNum, 10, 10) console.log(result); //100 |
Functions as object methods
A function declared inside an object or class is known as a method (or object method).
For example, the following code declares the Person object. It contains a property name
& addNum
. addNum
property contains a function. Hence it is called a method. We invoke it as person.addNum(10,10)
1 2 3 4 5 6 7 8 9 10 11 | let person = { name : "Alex", addNum : function(a:number,b:number) { console.log(a+b) } } person.addNum(10,10) |
A function is a free-floating object that exists independently. We expect that the addNum belongs to the person object. But in reality, you can take it out and assign it some other variables outside the Person object
In the following example, we assign addNum to a variable addNum1. Since the functions are objects, they are copied by reference. Hence both addNum
& addNum1
points to the same function.
1 2 3 4 5 6 7 8 9 10 11 12 13 | let person = { name : "Alex", addNum : function(a:number,b:number) { console.log(a+b) } } let addNum1=person.addNum; addNum1(1,10) //11 |
Function Hoisting
Now, look at the following code. We have invoked the calcArea
function before its declaration. But this code works without any errors. This is because of Hoisting.
Hoisting is JavaScript behavior where it moves all the declaration statements to the top. Hence even if we declare the calcArea
at the end of the file, JavaScript moves it to the top.
1 2 3 4 5 6 7 8 9 10 11 12 | //Invoke the function let result = calcArea(10,10) console.log(result) //Declare the function function calcArea (width:number, height:number) { let result = width * height; return result; }; |