Setting optional parameters in Functions or Classes in TS

avatar
Borislav Hadzhiev

Last updated: Feb 27, 2024
7 min

banner

# Table of Contents

  1. Setting optional parameters in Functions using TypeScript
  2. Omit one optional parameter while providing another in TS
  3. Define optional Parameters in a Class constructor in TS

# Setting optional parameters in Functions using TypeScript

Use a question mark to set an optional parameter in a function in TypeScript.

If set to optional, the parameter can have a type of undefined or the specified type, because unspecified parameters get the value undefined.

index.ts
function sum(a: number, b?: number) { if (b) { return a + b; } return a + a; } console.log(sum(10)); // ๐Ÿ‘‰๏ธ 20 console.log(sum(10, 3)); // ๐Ÿ‘‰๏ธ 13

setting optional parameters in functions

The code for this article is available on GitHub

The code sample sets an optional parameter without a default value.

Here is an example of marking a parameter as optional with a default value.

index.ts
function multiply(a: number, b = 10) { return a * b; } console.log(multiply(5)); // ๐Ÿ‘‰๏ธ 50 console.log(multiply(5, 2)); // ๐Ÿ‘‰๏ธ 10

marking parameter as optional with default value

You can also mark a property in an object parameter as optional.

index.ts
function getEmployee({ name = 'Bobby', salary, }: { name?: string; // ๐Ÿ‘ˆ๏ธ Mark optional salary: number; }) { return { name, salary }; } // ๐Ÿ‘‡๏ธ {name: 'Bobby', salary: 100} console.log(getEmployee({ salary: 100 }));

mark property in object parameter as optional

In the first example, we marked b parameter as optional.

index.ts
function sum(a: number, b?: number) { if (b) { return a + b; } return a + a; } // โœ… These 2 lines are the same console.log(sum(10)); // ๐Ÿ‘‰๏ธ 20 console.log(sum(10, undefined)); // ๐Ÿ‘‰๏ธ 20

The function can be invoked without providing the parameter, which sets the value of b to undefined.

Not providing the parameter and providing a parameter with a value of undefined is the same.

# A required parameter cannot follow an optional parameter

Note that a required parameter cannot follow an optional parameter.

index.ts
// โ›”๏ธ Error: A required parameter cannot // follow an optional parameter.ts(1016) function sum(a?: number, b: number) { }

You should always specify the optional parameters at the end of the function's parameter list.

# Setting optional parameters implicitly

You can also set a function parameter to optional implicitly - by providing a default value for it.

index.ts
// โœ… Optional parameter with a default value function multiply(a: number, b = 10) { return a * b; } console.log(multiply(5)); // ๐Ÿ‘‰๏ธ 50 console.log(multiply(5, 2)); // ๐Ÿ‘‰๏ธ 10

setting optional parameters implicitly

The code for this article is available on GitHub

Notice that we didn't have to use a question mark ? to mark the b parameter as optional.

We also didn't have to type the parameter, because TypeScript is able to infer its type based on the default value.

You should always set default values at the end of a function's parameter list.

If you want to use the default value of a parameter but need to specify values for some of the next parameters, pass undefined for the specific parameter.

# Setting the properties in an object parameter to optional

When you have a function that takes an object as a parameter, you might need to set properties in the object to optional or set the entire object to optional.

Here is an example that sets a property in an object parameter to optional.

index.ts
function getEmployee({ name = 'bobby hadz', // ๐Ÿ‘ˆ๏ธ default value salary, }: { name?: string; // ๐Ÿ‘ˆ๏ธ Mark optional salary: number; }) { return { name, salary }; } // ๐Ÿ‘‡๏ธ { name: 'bobby hadz', salary: 100 } console.log(getEmployee({ salary: 100 }));
The code for this article is available on GitHub

We set the name property in the object to optional and provided a default value for it.

You don't have to provide a default value if you don't need one, but you have to mark the property as optional even if you provide a default value.

Let's look at how you would set the entire object parameter to optional.

index.ts
function getEmployee({ name, salary, }: { name?: string; salary?: number } = {}) { return { name, salary }; } // ๐Ÿ‘‡๏ธ {name: undefined, salary: undefined} console.log(getEmployee());

We used a question mark to set all properties in the object to optional and provided an empty object as the default value.

# Omit one optional parameter while providing another in TS

To omit one optional parameter, while providing another in a TypeScript function, pass an undefined value for the optional parameter you want to omit and provide the value for the next parameters.

index.ts
function logArguments(num: number, str?: string, arr?: string[]) { console.log(num); console.log(str); console.log(arr); } // ๐Ÿ‘‡๏ธ omit the second parameter (providing 3rd) logArguments(100, undefined, ['a', 'b', 'c']); // ๐Ÿ‘‡๏ธ omit the third parameter logArguments(100, 'hello'); // ๐Ÿ‘‡๏ธ omit the second and third parameters logArguments(100);
The code for this article is available on GitHub

The logArguments function has 2 optional parameters - the second and third in its parameter list.

If we need to omit the second parameter and provide a value for the third, we have to pass a value of undefined for the second parameter.

Passing an undefined value for a function parameter is the same as not providing a value at all.

If you don't pass a value for an optional parameter, the parameter gets assigned a value of undefined.

Note that a required parameter cannot follow an optional parameter.

index.ts
// โ›”๏ธ Error: A required parameter cannot follow an optional parameter.ts(1016) function logArguments(a?: number, b: number) { }

You should always specify the optional parameters at the end of the function's parameter list.

You can also set a function parameter to optional implicitly - by providing a default value for it.

index.ts
function logArguments(num: number, str = 'hello', arr?: string[]) { console.log(num); console.log(str); console.log(arr); } // ๐Ÿ‘‡๏ธ omit the second parameter (providing 3rd) logArguments(100, undefined, ['a', 'b', 'c']); /** * Values logged: ๐Ÿ‘‡๏ธ * 100 * "hello" * ['a', 'b', 'c'] */

We set a default value for the second parameter of the function. This effectively makes the str parameter optional.

We passed an undefined value for the parameter when calling the function, which means that the value of str in the function's body will be hello.

Notice that we didn't have to use a question mark ? to set the parameter str as optional.

We also didn't have to type the parameter, because TypeScript is able to infer its type based on the default value.

# Define optional Parameters in a Class constructor in TS

You can use a question mark to define optional parameters in a class constructor function.

Alternatively, you can set a default value for the parameter.

Here is an example of providing default values.

index.ts
class Employee { // ๐Ÿ‘‡๏ธ provide default values constructor( public id = 0, public name = '', public tasks: string[] = [], ) { this.id = id; this.name = name; this.tasks = tasks; } } const employee = new Employee(); console.log(employee.id); // ๐Ÿ‘‰๏ธ 0
The code for this article is available on GitHub

Here is an example of marking the parameter as optional.

index.ts
class Person { // ๐Ÿ‘‡๏ธ mark as optional constructor(public address?: { country: string; city: string }) { this.address = address; } } const person = new Person(); console.log(person.address); // ๐Ÿ‘‰๏ธ undefined

The first class uses default values for the parameters in the constructor to mark them as optional.

Notice that we didn't have to type the id and name parameters because their type can be inferred based on the provided default values.

However, if you provide a default value for an array or object parameter, it's best to explicitly type the parameter.

If you omit the parameter when instantiating the class or explicitly pass an undefined value for it, the parameter gets assigned the default value.

index.ts
class Employee { // ๐Ÿ‘‡๏ธ provide default values constructor(public id = 0, public name = '', public tasks: string[] = []) { this.id = id; this.name = name; this.tasks = tasks; } } const employee = new Employee( undefined, undefined, ['design', 'development'], ); console.log(employee.id); // ๐Ÿ‘‰๏ธ 0 console.log(employee.tasks); // ๐Ÿ‘‰๏ธ ['design', 'development']

You can explicitly pass undefined if you want to use the default value for one of the first parameters, but specify a value for one of the latter ones.

# Marking a constructor parameter as optional

Alternatively, you can mark a constructor parameter as optional by using a question mark.

index.ts
class Person { // ๐Ÿ‘‡๏ธ mark as optional constructor(public address?: { country: string; city: string }) { this.address = address; } } const person = new Person(); console.log(person.address); // ๐Ÿ‘‰๏ธ undefined
The code for this article is available on GitHub

The address parameter is marked as optional. In other words, it can either be an object with the country and city properties or have an undefined value.

Note that required parameters in a function cannot follow optional ones.

index.ts
class Employee { // โ›”๏ธ Error: A required parameter cannot follow an optional parameter.ts(1016) constructor(public id?: number, public name: string) { this.id = id; this.name = name; } }

The id parameter is marked as optional, so it can't be followed by the name parameter, which is required.

However, you could have optional parameters towards the beginning of the function's definition that are followed by parameters with default values.
index.ts
class Employee { // โœ… This works constructor(public id?: number, public name = '') { this.id = id; this.name = name; } } const employee = new Employee(); console.log(employee); // ๐Ÿ‘‰๏ธ {id: undefined, name: ''}

The id parameter is optional and is followed by the name parameter which has a default value.

If your constructor function takes an object parameter, you can use the same approach to mark some of its properties as optional.

index.ts
class Person { constructor(public address: { country: string; city?: string }) { this.address = address; } } const person = new Person({ country: 'Chile' }); console.log(person.address); // ๐Ÿ‘‰๏ธ {country: 'Chile'}

The city property is marked as optional, however, the country property is required.

Here is an example of a constructor function that takes an object with an optional property and sets a default value for the entire object.

index.ts
class Person { constructor( public address: { country: string; city?: string } = { country: '' }, ) { this.address = address; } } const person = new Person(); console.log(person.address); // ๐Ÿ‘‰๏ธ {country: ''}

We provided a default value for the entire object parameter, so we didn't have to pass an object when instantiating the class.

Note that we had to specify the country property in the default object because it is required.

If you don't want to provide a default value for any of the properties and want to set an empty object as the default, mark all of the properties as optional.

index.ts
class Person { constructor(public address: { country?: string; city?: string } = {}) { this.address = address; } } const person = new Person(); console.log(person.address); // ๐Ÿ‘‰๏ธ {}

If you need to pass a function as a parameter, check out the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev