TypeScript Optional and Default Parameters

In TypeScript, by default, all the method parameters are mandatory. To support a variable number of parameters, we can declare a few parameters to be optional. In addition, we can define the default values for the method parameters as well.

//param2 is optional
//param3 has default value ""
//A parameter cannot be optional and default, at the same time.
//No mandatory parameter can appear after optional or default parameters

function functionName(param1 :string, param2 ?:string, param3 :string = ""):string {

    //...
}

1. TypeScript Optional Parameters

Optional parameters allow for cleaner and more adaptable code when working with libraries or APIs that expect functions with varying numbers of arguments.

1.1. Syntax

In TypeScript, we can declare optional parameters by adding a question mark (?) after the parameter name in the function declaration.

In the following function declaration, param2 and param3 are optional and can be omitted when invoking the function.

function functionName(param1: type, param2?: type, param3?: type) {

  //..
}

Note that optional parameters must appear at the last of the parameters list. A required parameter cannot follow an optional parameter. The following declaration is NOT permitted because the param3 is a required parameter and appears after the optional parameter param2.

function functionName(param1: type, param2?: type, param3: type) {

  //..
}

1.2. Basic Usage of Optional Parameters

A simple example to demonstrate the usage of an optional parameter is fullName() function that takes three arguments: firstName, middleName, and lastName. The middleName is an optional parameter.

function fullName(firstName :String, lastName :String, middleName ?:String):string {
    return middleName ? 
    `${firstName} ${middleName} ${lastName}` : `${firstName} ${lastName}`;
}

console.log(fullName("Lokesh", "Gupta"));	//"Lokesh Gupta" 

console.log(fullName("Lokesh", "Gupta", "Kumar"));	//"Lokesh Kumar Gupta" 

2. TypeScript Default Parameters

Default parameters help by providing sensible or commonly used values for certain parameters, but still allow flexibility to override those default values when necessary.

2.1. Syntax

TypeScript allows assigning a default value to a parameter if no value or undefined is provided when invoking the function. We can provide the default values for optional parameters as well as mandatory parameters.

In the following function declaration, param1 is a mandatory parameter and param2 is an optional parameter. Both have been assigned the default values defaultValue1 and defaultValue2, respectively.

function functionName(param1: type = defaultValue1, param2: type = defaultValue2) {

  //...
}

Similar to optional parameters, the default parameters must come after the mandatory parameters in the function declaration.

2.2. Example: Basic Usage of Default Parameters

In the following example, the function fullName() specifies the default value the last parameter middleName as an empty string.

function fullName(firstName :String, lastName :String, middleName :String = ""):string {
    return `${firstName} ${middleName} ${lastName}`;
}

console.log(fullName("Lokesh", "Gupta"));		//"Lokesh  Gupta"

console.log(fullName("Lokesh", "Gupta", "Kumar"));	//"Lokesh  Gupta" 

2.3. Example: Default Parameters with Complex Types or Expressions

The default values are not limited to simple types. We can specify the complex types or expressions that evaluate the value in runtime.

Suppose we have User type in the application that can perform various actions in the application.

interface User {
    id: number;
    name: string;
    role: string;
}

function createUser(id: number = 1, name: string = "Test User", role: string = "GUEST"): User {
    
  return { id, name, role };

The isUserActionAllowed() has been created to check if a certain action is allowed for a User. If there is no user logged in the application, the default user with GUEST role must be used.

function isUserActionAllowed(action: string, user: User = createUser()): boolean {
    
    console.log("USER ROLE is " + user.role);

    //function implementation
    return false;
}

console.log( isUserActionAllowed("CREATE_ITEM", createUser(100, "Lokesh Gupta", "ADMIN")) );   //"USER ROLE is ADMIN"


console.log( isUserActionAllowed("CREATE_ITEM") ); //"USER ROLE is GUEST" 

3. An Optional Parameter cannot have a Default Value

It is not allowed to declare a parameter to be optional and default, both. A parameter can be either optional or can have the default value. Doing this will raise the compiler error: “Parameter cannot have question mark and initializer“.

//Compiler Error - Parameter cannot have question mark and initializer
function fullName(firstName :string, lastName :string, middleName ?:string = ""):string { ... }

Although, we can define separate optional and default parameters in the same function declaration.

//Allowed to specify separate default and optional parameters in the same function
function fullName(firstName :string = "", lastName :string = "", middleName ?:string):string { ... }

4. Conclusion

Typescript default parameters and optional parameters provide a convenient way to build APIs that can accept a variable number of arguments and specify sensible default values where necessary. By combining default parameters with optional parameters, we can create functions with even greater flexibility.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.