TypeScript - Parameterized a Function

Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined.

While calling a function, there are two ways that arguments can be passed to a function −

S.No. Call Type & Description

Call by value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.


Call by pointer

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter

Following are the ways in which parameters can be used by functions −

Positional Parameters

function func_name( param1 [:datatype], ( param2 [:datatype]) {   

Example: Positional parameters

function test_param(n1:number,s1:string) { 
test_param(123,"this is a string")
  • The snippet declares a function test_param with three parameters namely, n1, s1 and p1.

  • It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameter is considered to be of the type any. In the above example, the third parameter will be of the type any.

  • The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error.

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10
function test_param(n1, s1) {
test_param(123, "this is a string");

The output of the above code is as follows −

this is a string