Working with TypeScript Function Arguments
This guide analyzes how to work with function arguments in a TypeScript program. This includes a walk through of: optional, default, and rest arguments.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Now that you have a good foundation on what functions are and the syntax for using them in typescript in this guide we're going to walk through some more advanced ways that we can use function arguments. I'm going to start off by talking about how can we can make arguments optional and typescript.

Optional Arguements

So I'm going to create a function here called Print address and print address is going to take a couple arguments. First it's going to take a street and the type is going to be string. And the next thing it's going to do is it's going to take a street 2 and this one also is going to be of type string. Now inside of this I want to just console log. Both of these items out on two different lines so say. Street and then we'll say Street 2. Now this would work if I come down and run print address and now I can do 123 any street and then pass in the next argument as suite 540. And if I come and run this program. You can see that this works properly.

function printAddress(street: string, streetTwo: string) {
  console.log(street);
  console.log(streetTwo);
}

printAddress(‘123 Any St, ‘Suite 540’);

However if you think about addresses you know there's a lot of times where people don't have a suite they just have the first street. So we need the ability to make this optional. If I get rid of the second street right here. You're going to see that this now throws an error in it says the supplied parameters do not match any signature of the method. So that's our problem is it's expecting two items and we're only passing in one. So the way that we can fix that is right after the argument name and before the colon type in a question mark. And what this question mark is going to do is it's going to say that this argument is actually optional. So now what you'll see is if we run this program.

function printAddress(street: string, streetTwo?: string) {
  console.log(street);
  console.log(streetTwo);
}

printAddress(‘123 Any St, ‘Suite 540’);

Instead of an error it actually prints out it does print out undefined instead of just printing a blank out. So that's fine the way we can fix it is we can say enough. If Street 2. And then. Inside curly brackets put this code here. And now if we run this again you'll see that it doesn't print anything out just like we want.

function printAddress(street: string, streetTwo: string) {
  console.log(street);
  if (streetTwo) {
    console.log(streetTwo);
  }
}

printAddress(‘123 Any St);

So by placing this if statement it checks to see if this value exists if it does then Ill print it out. And if not it's going to skip it and we can test this out by adding a value if I pass in suite 540. And run this code. You'll see that the first time it goes through it skips the argument and the next time it prints it out which is exactly what we want. So that is how you can use optional arguments.

Default Arguements

Now there also comes a time where you may want to have default arguments. So a default argument is an argument that you want to provide a default for in the function signature. So even if the user or the program doesn't pass in a month or pass in an argument it's still going to be able to have a default. And then we can simply override it when we want to change it.

So a good example would be say that this print Address function is attached to a program that for 99 percent of the programs that it runs the addresses are in Arizona. So what I can do is pass in another argument called state and I can set this equal to. So instead of doing a colon I can set state equal to AZ. And because I'm setting state equal AZ we know that the data type or state is going to be a string. And now if I come up to console log. And replace it with state. Now even though I've not supplied any state if I come and run this program. You'll see that a state will be provided. And as you can see right there both times that it ran.

function printAddress(street: string, streetTwo?: string, state = ‘AZ’) {
  console.log(street);
  if (streetTwo) {
    console.log(state);
}

printAddress(‘123 Any St’);
printAddress(‘123 Any St’, ‘Suite 540’);

We've got Arizona in both spots now. If I duplicate this line and actually want to pass in another item so if I want to pass a Utah in for the state this will actually override the value. And now you can see that for the third call where we passed Utah in as an argument you can see this now actually prints out with the state that we want it.

function printAddress(street: string, streetTwo?: string, state = ‘AZ’) {
  console.log(street);
  if (streetTwo) {
    console.log(state);
}

printAddress(‘123 Any St’);
printAddress(‘123 Any St’, ‘Suite 540’);
printAddress(‘123 Any St’, ‘Suite 540’, ‘UT’);

So this third item here is simply a default value it's no problem to override by simply passing that parameter in. Now one thing that I want to make clear here because this may kind of create a bug for you if you if you try to experiment with it is let's say I wanted to try to add another thing and I wanted to add a zip code of type string. You'll see that this has an error and you may wonder why does this have an error. And why now are all of these completely invalid. And the reason for this is because you cannot have a required value which here we're not saying that Zips optional and you cannot have a required value after a optional value. And the reason for this is let's ignore our little squiggly lines here and let's pretend that we have another call, different address we call street right here. But let's say that there is no sweet 540 and we call Utah and then we want to pass in a value of 85251. The reason why this won't work is because of this optional value. It is going to throw an error because it's going to look and count it's going to say OK this needs to be mapped to street. Now this is this getting map to street to or what is this getting mapped to? So it doesn't even typescript doesn't even let you play around with the idea of being able to mismatch and create match mapping issues with your arguments. And so if you wanted to add any other parameters you would have to add them before any of the optional values as you can see right here. This would work fine. I'm not going to keep it in there because out there your values often are wrong and get rid of this last call. However that is an important thing to keep in mind is that if you have any optional values like this they have to be placed at the very end of the method of the function arguments.

Now one spot where that's not the case is for default arguments default arguments could be placed anywhere you want at. I could take state. Put it in front of street and everything would still work perfectly fine. This one would be let's see. This one is saying that there is an error supplied primers do not match any signature. And oh and that's just because you would need to have a couple different items inside of this one. And I'm going to put this back where it belongs. But as you could see these other ones that had multiple items these ones actually worked. This one didn't because we had this value which was trying to override the state value. And then there was still the street value which was required. So the good rule of thumb is to place all of your optional your default items closer to the end and your optional ones have to be at the end just to make sure you don't have any confusion with your method of mapping.

Ok now I'm going to comment this out. Moving down. I'm going to create another method and what this one is going to do is we've talked about default arguments we've talked about optional arguments but I also want to show how you can have a splat argument but in typescript It's called a rest argument. And what it means is a rest of the items and what it really stands for is the ability to have an array of values. So I think the example I came up with this one we'll explain it. So I'm going to create a method called lineup card and this lineup card method is going to take a team name which is going to be a string. And then it's going to print out all of the players for a team and the method argument that we can use is … and then whatever you want to call the argument name. So for this one I'm going to call it players and this is going to be a string array. So right here you can see that we have team which is a string and this is the argument name and it's a string. This one because we had these three dots here what typescript is going to do is it's going to say OK right here any of the values and it could be an unlimited number. Any of them are going to be treated like an array when they get passed in. So I'm going to do the curly braces and inside of this I'm going to do some console log statements. The first one I'm going to do is as a team and I'm going to concatenate that with the name of the team. And next thing I do is I'm going to use a for loop. So I'm going to say for a let player of players and we have access to the player's array because it's an argument here and because it's a … it's a rest argument. We know that that value is going to be an array and we can iterate over it. And here we're just going to console log out the player. And just as a review player here is the iterator variable this could just as easily be X or I or whatever you want it to be. So this is just a variable in it because we're using a for of loop every single time we iterate through the player's array. This is going to be equal to the value that we're looping through. So now if I come down here. And call lineup card I first pass in the name of the team I’m going to say Astro's and then I pass in as many values as I want. Now I'm not passing in an array. So if I try to pass in a string array here saying two of Altuve, Corerra And, Bregman. This is not going to work. As you can see we have errors right here. And so the reason for this is because a red star it converts it to an array. You don't pass in an array. So what I'm going to do is get rid of. The brackets and it's just going to look like a regular set of string arguments. And now I believe that's all right if I come here and run this you can see that it prints out the team name and then iterates over our list of players for the lineup card just like this.

function lineupCard(team: string, …players: string[]) {
  console.log(‘Team: ‘ + team);
  for (let player of players) { 
    console.log(player);
  }
}

lineupCard(‘Astros’, ‘Altuve’ ‘Correra’, ‘Bregman’);

So just in review this is a method that has a regular string argument and then it also has what's called a rest argument and a rest argument takes in a array it doesn't have to be a string array it could be anything if this was player jersey numbers it could be a number array right here. And then inside of the function whatever this value is you just treat it as a array. You treat it as an array so you loop over ADD or you do any kind of iteration that you'd normally do with a typical array. So those are a few different ways that you can add optional. Default and then rest arguments inside of a typescript function.

Resources