Conteúdo do Curso
Introduction to TypeScript
Introduction to TypeScript
Optional Parameters
Sometimes there are situations where we need to pass a varying number of parameters to a function. For instance, when registering on a website, we may be asked to enter a mobile phone number, but it's optional. There are various solutions to this problem, from overloading functions to creating separate functions for each case. But let's explore a handy feature of functions in TypeScript – optional parameters.
In simple terms, these are parameters that you don't have to pass to the function.
Let's look at an example:
function register (username: string, password: string, phoneNumber?: number) { if (phoneNumber) { console.log(`New user with username: '${username}', password: '${password}' and phone number: '${phoneNumber}'`); } else { console.log(`New user with username: '${username}' and password: '${password}'`) } } register('Bob', 'qwerty123', 17871233210) register('Alice', '123456789')
The function above registers a user. We need to provide a username
, password
, and a phoneNumber
. The phone number is an optional parameter. Take note of the syntax: when specifying this parameter, we add a question mark. We are literally questioning the existence of this parameter. Maybe it will be there, maybe not.
Inside the function, we check whether the phone number is provided. If it is, we print user information to the console, including the phone number. If not, we print user information without the phone number.
Additionally, this user should be saved in the database, but that's a more advanced topic that we will definitely cover in future courses.
Now, let's look at another example of using optional parameters:
function greeting(name: string, surname?: string) : string { if (!surname) { return(`Welcome, ${name}`); } else { return(`Welcome, ${surname} ${name}`) } } let first = greeting('Grzegorz', 'Brzęczyszczykiewicz'); let second = greeting('Peter') console.log(first) console.log(second)
In this example, we've created a very simple greeting method. A person can choose to provide his or her last name or leave it empty. Our program will greet the person regardless. I hope the algorithm is clear. We specify an optional parameter, check for its presence using an if
statement, and proceed with our actions accordingly.
Optional parameters are indeed a very useful and frequently used feature because we don't always need all the data we pass to our function.
Obrigado pelo seu feedback!