Learn to create functions in typescript and function type declaration. We will also see how to declare and pass optional parameters, setting default value for any parameter; and rest parameters with easy-to-follow examples.
Table of Contents 1. Creating a function 2. Function Types 3. Optional Parameters 4. Parameters with Default Values 5. Rest Parameters
1. Create a function in TypeScript
In TypeScript, we can create a function in two ways.
-
Named Functions
The named functions are written in traditional JavaScript style.
console.log( showMyName("Lokesh") ); // Hi! Lokesh function showMyName (name: string): string { return `Hi! ${name}`; }
-
Anonymous Function or Function Expression
Anonymous functions don’t have names. They are assigned to variables.
console.log(showMyName("Lokesh")); //Error - Define functional expression first. let showMyName = function(name: string): string { return `Hi! ${name}`; }; console.log(showMyName("Lokesh")); //Hi! Lokesh
The JavaScript interpreter can evaluate a function declaration as it is being parsed (variable hoisting).
On the other hand, the function expression is part of an assignment and will not be evaluated until the assignment has been completed.
2. Function Types
In TypeScript, everything is a type. Functions are also types. We can declare a variable’s type to be function using the keyword Function
.
let showMyName: Function = function(name: string): string { return `Hi! ${name}`; };
In above example, showMyName
is a variable which can point to a Function
type only.
If we don’t specify a type of variable, TypeScript infers the type automatically.
3. Optional Parameters to a Function
Unlike JavaScript, the TypeScript compiler will throw an error if we attempt to invoke a function without providing the exact number and types of parameters that its signature declares.
To solve this problem, we can use optional parameters using question mark sign ('?'
). In below example, message
is marked as optional parameter.
let showMyName = function(name: string, message?: string): string { return `Hi! ${name} {message}`; }; showMyName(); //Error showMyName('Lokesh'); //Hi! Lokesh showMyName('Lokesh', 'How are you?'); //Hi! Lokesh How are you?
4. Parameters with Default Values
Optional parameters are great feature but leave us with the logic to implement the scenarios where it’s values can be undefined
. It require lots of null
checks and if-else
blocks.
A better approach would be to have default values of these parameters, rather than to declare them optional. If will lead to more cleaner code and easy maintenance of code.
let showMyName = function(name: string, message: string = 'How are you?'): string { return `Hi! ${name} {message}`; }; showMyName('Lokesh'); //Hi! Lokesh How are you? showMyName('Lokesh', 'How are you buddy?'); //Hi! Lokesh How are you buddy?
2. We cannot make any parameter optional and default both. Only one type is allowed.
5. REST Parameters
Sometimes, we may want to create functions which can have undetermined number of parameters. For one or two parameters, we can use optional parameters or default values. But what if number of parameters is not known, or can vary at runtime.
For example, we are reading input field values and that can vary due to dynamic UI. Here rest parameters will help you.
The REST parameter syntax allows us to represent an indefinite number of arguments as an array.
- To create REST parameter, use
ellipsis
i.e. three dots ('...'
) before the variable name, as seen in spread operator. - A REST parameter must be of an array type or we will get a compilation error.
- Theoretically, there is no specific limit to the maximum number of arguments.
let addInputValues = function(...values: number[]): number { let result = 0; for (let val of values) { result += val; } return result; }; addInputValues(); //OK - You can choose not to pass anything as well addInputValues(1, 1); //OK addInputValues(1, 2, 3); //OK addInputValues(1, 2, 3, 4, 5, 6); //OK
Drop me your questions in comments section.
Happy Learning !!
Leave a Reply