HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TypeScript / TypeScript Functions – REST, Optional and Default Parameters

TypeScript Functions – REST, Optional and Default Parameters

Learn to create functions, function type declaration, optional parameters, default parameters and rest parameters with example.

Table of Contents

Create function
Function Types
Optional Parameters
Default Parameters
Rest Parameters

Create function

In TypeScript, you can create functions in two ways.

  1. Function Declarations

    These are named functions written in traditional JavaScript style.

    console.log( showMyName("Lokesh") ); // Hi! Lokesh
    
    function showMyName (name: string): string { 
        return `Hi! ${name}`; 
    } 
    
  2. Function Expressions

    These functions don’t have names. They are assigned to

    console.log(showMyName("Lokesh"));	//Error - Define functional expression first.
    
    let showMyName = function(name: string): string { 
        return `Hi! ${name}`; 
    };
    
    console.log(showMyName("Lokesh"));	//Hi! Lokesh 
    
Please note that both function declarations looks similar BUT they are not. 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.

Function Types

In TypeScript, everything is type, functions are also types. You can declare a variable’s type to be Function as shown.

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 you don’t specify a type of variable, TypeScript infers the type automatically.

Optional Parameters

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, you 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?
It is important to note that the optional parameters must always be located after the required parameters in the function’s parameter list.

Default Parameters

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?	
1) Note that same as optional parameters, default parameters must also be located after the required parameters in the function’s parameter list.
2) You cannot make any parameter optional and default both. Only one type is allowed.

REST Parameters

Sometimes, you may want to create functions which can have undetermined number of parameters. For one or two parameters, you can use optional parameters or default parameters. But what if number of parameters are not known, or can vary at runtime.

e.g. You 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.

  1. To create REST parameter, use ellipsis i.e. three dots ('...') before the variable name.
  2. A REST parameter must be of an array type or we will get a compilation error.
  3. 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 !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Ashwin

    March 13, 2020

    What is the difference between rest parameters and passing an array as optional parameter in function? Both does the same work

  2. g8up

    February 15, 2019

    what if the rest params array have multiple types ?

    • IM 12

      January 27, 2020

      It wouldn’t work, they have to be similar types.

Comments are closed on this article!

Search Tutorials

TypeScript Tutorial

  • TypeScript – Introduction
  • TypeScript – Types
  • TypeScript – Union Types
  • TypeScript – String Literal Types
  • TypeScript – var, let and const
  • TypeScript – Template Strings
  • TypeScript – Arithmetic Operators
  • TypeScript – Logical Operators
  • TypeScript – Comparison Operators
  • TypeScript – for Loop
  • TypeScript – Spread Operator
  • TypeScript – Arrays
  • TypeScript – Enums
  • TypeScript – Map
  • TypeScript – Set
  • TypeScript – Functions
  • TypeScript – Function Overloading
  • TypeScript – Transpiler
  • TypeScript – Truthy and falsy
  • TypeScript – == vs ===
  • TypeScript – undefined vs null
  • TypeScript – Variable Hoisting
  • TypeScript – tsconfig.json

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)