Last updated: Feb 27, 2024
Reading timeยท7 min
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
.
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
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.
function multiply(a: number, b = 10) { return a * b; } console.log(multiply(5)); // ๐๏ธ 50 console.log(multiply(5, 2)); // ๐๏ธ 10
You can also mark a property in an object parameter as optional.
function getEmployee({ name = 'Bobby', salary, }: { name?: string; // ๐๏ธ Mark optional salary: number; }) { return { name, salary }; } // ๐๏ธ {name: 'Bobby', salary: 100} console.log(getEmployee({ salary: 100 }));
In the first example, we marked b
parameter as
optional.
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.
Note that a required parameter cannot follow an optional parameter.
// โ๏ธ 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.
You can also set a function parameter to optional implicitly - by providing a default value for it.
// โ 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
Notice that we didn't have to use a question mark ?
to mark the b
parameter
as optional.
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.
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.
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 }));
We set the name
property in the object to optional and provided a default
value for it.
Let's look at how you would set the entire object parameter to optional.
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.
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.
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 logArguments
function has 2
optional parameters -
the second and third in its parameter list.
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.
// โ๏ธ 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.
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.
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.
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
Here is an example of marking the parameter as optional.
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.
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.
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.
Alternatively, you can mark a constructor parameter as optional by using a question mark.
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 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.
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.
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: