Typescript Functions | Basics Tutorial for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome I'm Dave today we'll learn about typescript type aliases functions literal types and the never type I'll provide links to example source code and all resources in the description below today's starter code is our code from lesson three and we're going to use just a little bit of this code so I'm going to scroll down to about line 38 and you can see I have the interfaced guitarist highlighted that we created in lesson three I'm going to use Ctrl X to cut that out and then Ctrl a to select the rest of the code and just press backspace to delete it now I'll paste this interface back in and if you remember from the previous lesson before we created this interface we use the keyword type and then of course we had to have an equal sign over here as well to represent this object what we're creating is called a type Alias but this can apply to more than just objects so I'm going to comment that up here type aliases is what we're going to discuss and let's create another type Alias so I'll say type and then I'm going to say string or number we can set this equal to a union type that is string or number and now instead of having to type out the union type string or number if we were using this in several places in our application we could just use this string or number type likewise we could add more to the union type or we could just Define another type if we want to so let's do another one here and let's say type string or number array and let's go ahead and set this equal to what we see in the guitarist below so now we have string or number and it's also an array and now that we've done that we can actually use this type inside of our guitarist object that we created so we're using a type Alias inside of another type Alias and this works as well or let's say we have a type that is a user ID and it could be a Stringer number as well and we've already defined the string or number type Alias above so we could just set this equal to string or number and this would also work because now type user ID is going to be a string or number Union just like the string or number type that we assigned Above So essentially we are representing our typescript types with a different name and that is what is called an alias so we are creating type aliases for our typescript types now again if you have the question in your mind about why is a type different than an interface we cannot do this with an interface so here I'll say post ID and try to set this equal to string or number and that just won't work so interfaces think about those more as objects or classes if you will and types you can think of as an alias for any type of typescript type that we might assign now let's look at literal types I'll comment that right here a literal type or types and I'll assign say let my name and I'm going to assign it my actual name instead of saying string number or Boolean for example or a union type of any of those and now when I Mouse over let's look at the intellisense and it says let my name or my name is type Dave now that's different than what we've seen before so that is a specific assignment it's a literal assignment so if I try to set my name equal to John typescript does not like that so instead of setting my name equal to John I can only set it equal to my name which is Dave but we might want to have a variable that would be a little bit more useful than that so let's say let username and then we'll use a union type here with literal assignments so we could say Dave or John or Amy for example now any of those values would be valid for username so we could set username and then we could set it equal to and notice we get intellisense to help us out now built into typescript as well so it could be Amy Dave or John here inside of Visual Studio code so we'll just assign Amy and that is a valid value but any other name in there say Rachel nope it doesn't like that so it can only be Dave John or Amy so once again when I type the single quote we get intellisense help and I'll assign Amy so a literal type with only one value is much like saying const my name equals Dave because that would not be reassignable and in this example the only possible value is my name which is Dave for the my name variable however these can be very useful when you use the union type because now more than one value can be assigned and you might have a variable where only certain values are expected and you could do this with numbers as well so literal types can be very useful as well as keeping your code dry because you might assign this once to username and then use username in your code and you'll know it only expects these three values without specifying these every time and really you could go back to the aliases and say they could also keep your code dry because you're creating a type instead of possibly a somewhat long type definition with a union or something like that this is fairly short but instead of typing this every time of course you now have the type Alias you can refer to so a benefit of both literal types and type aliases could be keeping your code just a little drier and of course dry means don't repeat yourself it's that acronym d-r-y now let's look at functions so I'm going to return and I'll put functions here this is a bit of a review because we looked at a function called sum in previous lessons and this will be a review of that I'll just call it add instead but basically the same thing where we could have two variables A and B and then we'll have an arrow function here for this example and I'm just going to return a plus b now we've already learned that typescript can infer what these are but you can see typescript does not like what we have here we've got a line underneath parameter a implicitly has any type and we'll see the same for B so we have not put those types in explicitly and typescript would really like us to do that so let's go ahead and say both of these need to be number types and we could provide a space there as well and here I'll put number also and we don't need a space there after the type so just formatting a little so A and B are number type but notice when I Mouse over the function name add it also says it returns a number so it is still inferring what this function would return so we can supply that information as well by putting a colon right after parentheses and putting the type of data that the function will return now one thing we have not looked at is a function that does not have a return so let's create that I'll call this log message and this is going to accept a message and we'll assign the any type because we could be sending any type of data here that we want to log and then afterwards well I'm not going to say what type it is we'll let it infer and then we'll go ahead and assign it after so we're just going to console log whatever message we send in and it can be any data type now let's Mouse over log message and we can see the return type is void because it does not have a return so if we were to assign that we would do it in the same way we just say void and this void type is for functions that do not return anything so this is a side effect any function that would have a side effect that would not have an explicit return should be a void type of return data which essentially means there's no return at all so let's use our log message and we'll call that and we could pass in hello and typescript is fine with that I'm going to do shift alt and the down arrow to copy a couple of times we could also pass in our add function say we're going to add 2 and 3 and our add function is fine with that because those are two numbers passed in let's once again do our add function now let's pass in the string a and three and we'll get rid of that extra single quote there and it does not like that at all I need the extra parentheses there too so now we've got log message twice oh and I've got double and single quotes so no wonder it didn't like all of that here now we just have the error I expected which is saying that the argument type string is not assignable to the parameter type of number and we're getting that because that's our add function so we're passing in data that will not work with that so if we change this back to numbers like above it would be fine I just wanted to show that example to show that it still works inside even when we're calling a function inside or passing this in to another function I'm going to go ahead and save this data then I'm going to do control back to stick to open up a terminal window type tsc-w so it starts watching our typescript files and creates the JavaScript files we have learned how to set that up back in lesson one now that typescript is running let's go ahead and drag this over to the left I've got an empty browser here to the right I need to go into the build folder click my index.html click go live to launch live server so we run our code and now we should get this black background instead of the somewhat charcoal background I had in the other Tab and I'm going to control shift and I to open up Dev tools just so we can see our console log statements I'll also do uh well I'll select the main TS file that we're working in and then Ctrl B to hide the file tree so we can see our code here on the right but now we see our log messages besides the live reload enabled from live server we get hello and the number five okay I used Arrow functions both for the add function and the log message function but you do not have to use Arrow functions so I'm going to scroll up and create another function and we'll call this one subtract so I'll say let subtract it's going to equal a function I'm going to use the function keyword and then I'll give c as a parameter and it's also a number and D which is also a number and this is also going to return a number we could have curly braces here I'll press alt Z to wrap the code down just so we don't miss anything now we need to return C minus D now that we've completed the function typescript is happy no error Marks here and just note that this is wrapping down a line since I have the browser open on the right now and it's this is the return type here the number as well just following the parentheses just like we had above for add we're just taking up a little bit more room because we have a larger word here for subtract and we have the word function so this function also works just like add does except we're using the keyword function we're not creating an arrow function we're using the curly brace here just after the number type but it works in the same way and notice both of these functions actually have the same type signature here they both accept two number parameters and they return a number so this is where it could be useful to use a type especially if I know I'm going to create more math functions now actually I would want to create the type above both of these if I were to use it in these functions but I'm going to create it below and then just use it to another use it for another math function so I'll say type and then I want to say math function and then after that I'm going to say it equals a function with a parameter that is a number need to type number correctly and a second parameter is also a number and then it's going to return a number so there is our definition or our math function type and now if we were to create another math function such as multiply we could use this type so I'll just say let multiply and just right away I'll say this is a math function type then let's set this equal to a function and it has C and D as parameters and then I'm going to use a curly brace and inside of the function I'm going to return c times d and now typescript says this is okay so let's Mouse over multiply and you can see the type it is signed is math function which is an alias or this type definition that we put up here that has two number parameters and returns a number so now it should know our function is going to return a number and it expects the first and the second parameters to also be numbers so it infers that actually because we assign this type Alias to multiply so it expects math function to match so now I'll do one more log message and we'll call our multiply function and I'll say 2 times 2. and when we save we should get 4 in the console and we do I'll make the console just a little bigger there so we can really see that text too now when it comes to functions I like to use the type aliases more than I do in the interface but I do feel obligated to show that an interface is also an option with a function signature just like a type Alias is so I'm going to copy this down with shift alt and the down arrow once again I'll just comment out the type above for a moment and now I'll set this instead of a type to an interface but we once again have to change some things for an interface to work so we need to remove the equal sign and put a curly brace to start then I'm going to bring this down onto another line and then I'll put a curly brace to end but notice typescript still doesn't like The Arrow here we need to remove this Arrow function and we need to put in a colon right there so this is an interface for math function and when I save typescript compiles and we still get the same result here in the console so this also works but typically when I think of interfaces I'm thinking more about classes and being able to extend those which we'll learn about in the future and then when I'm thinking of functions and other basic types I'm thinking of type aliases so what I'm going to do is uncomment this type and then comment out the interface but leave it in there for you just so you can see both examples in the source code for this lesson we're not quite finished with functions yet because I want to cover optional parameters and default values as well so let's first look at optional parameters for our functions so I'm going to Define one more function I'll call it add all and I'll set this equal to a function that receives a number parameter and a second number parameter and a third number parameter this is an arrow function as well and then after that we're going to say return a plus we need the plus b plus C so that would add all three of those now we didn't say what the return type was that should also be a number here as well there is our add all function and that's fine when we require all three of those but we can say a parameter is optional by putting a question mark before the colon and now we have a problem here in typescript typescript put a little red line under our C and if I Mouse over it says this is possibly undefined look at the type of the C parameter it's not just number although we said it was it's number or possibly undefined because it's optional so for typescript to be okay with this we have to put in what is called a type guard and a type card Narrows down the type of value assigned to the variable so what we'll say here is if type of and then we can say C is not equal to undefined then we're going to return a plus b plus C so I just need to put that inside let typescript probably still won't be happy with the function because that's not the only possible result and notice here we have a red line under number it says the function lacks an ending return statement and the return type does not include undefined so it's not good if we just leave it like that so essentially we need an else but instead of an else I'm just going to put a return here as well because if it's not this it's going to return the other and I'll just say return a plus b and let's see if typescript is now happy and yes it is so if type c is not equal to undefined it's going to return the sum of all three parameters otherwise if type c is undefined it's just going to return the sum of A and B now I believe I mentioned it but remember that if you have an optional parameter it needs to be the last in the list your required parameters do need to come first so now I'm going to copy this down I'll just highlight all of this and do shift alt in the down arrow and then I'll change the name of the function and I'll just call it sum all which means essentially the same thing and here we currently have the same signature number number and a third optional number well let's change that to where this number is not optional but really it still kind of is because we're going to assign a default value now so if we don't Supply C it will be equal to 2 if it is not explicitly supplied when the function is called so C should never be undefined at this point so we could go ahead and remove the if statement and now we should be able to just put plus C once again and typescript is okay with this function so let's log some of these out with our log message function and I'm going to say add all and I'll put 2 and 3 and 2 so we should get 7 there and I'll copy this down and add all again and I will not supply the ending parameter for C and there we should get 5 because type the type of C will be undefined so it should just Add A and B now for the last one we'll do the sum all and I'll once again pass in 2 and 3 but we should once again get the value that we get for the first at all which should be 7 because C should be equal to 2. so now I'll save all three of these and yes we got 7 and then 5 and then 7 once again now unlike the rule we had for optional parameters and I should put default param value here um C is the last in the line as far as the parameters here but we could give a a default parameter so I'll give this and equals 2 as well and then if we were to call this and omit a we would have to explicitly pass undefined in because otherwise it would be assigned a so I know that's a little bit confusing but what we would have to do here and I should make that a different number let's make it something obvious like 10. so instead of the sum all we have at the end with 2 and 3 I would have to explicitly say undefined and that would be okay otherwise if we do this typescript doesn't like it because 3 is being assigned to a it's the first thing in so if you want it to skip over a you have to give it a value there so we'll say undefined and three and this would be rather obvious now that it should be 15. and that is because we have a 10 as a default value then we passed in the number 3 so that's 13 and then even though we didn't pass in C it also has a default value of 2 so that all adds up to 15. now if you remember our math function above that we defined with an alias type math function and this is the function signature we cannot do that with default values so that is one thing that cannot be achieved with an alias type or also the interface math function here default values will not work when we Define a function signature like this okay I'm going to scroll up for a little more room as we're not quite finished with functions yet we need to talk about r rest parameters and they look very much like the spread operator but it's when we pass them in as parameters to a function so I'm going to Define another function called total and this is going to be equal to a function that accepts a number for the first parameter no you know what I'll leave out the first parameter at first and I'll just say it's going to receive nums and notice I'm using a rest operator there for nums and then it is number and it should be an array so that represents an array full of numbers we don't even know how many numbers but that's what we have and then this function is going to return a number and then inside the function I'm going to return and then I'm going to use the nums array that is passed in I'm going to call reduce on the array because it's a good function for totaling up an array of numbers and now inside of reduce we'll have the previous value and the current value represented and then we just Arrow over and say previous plus current and now that we've done that our function is complete so let's look at what happens when we use log message and then we call Total we're going to have one two three and four all passed in now again notice I'm not putting an array here but this is represented as an array here because we used the rest operator so when I save we get the total of 10 over here which one plus two is three plus three is six plus four is ten that is correct so the reason this is called rest if you're not familiar with it it kind of means the rest of the parameters so this should always come at the end as well so if I were to represent this with another parameter first like I almost did in the beginning I could say a is a number it's required and then however many other numbers I want to pass in so I could just pass in two values say one and two and save and now of course we get 2 over here at the bottom and that's because I didn't use the a parameter notice it is still a little lighter here so let's now say a plus whatever we reduce from this rest params which is the array and I save now we get three so it took whatever I passed in in the beginning for a and then however many numbers remain and it represents those as an array so now we could say 1 2 3 and save and yes we get 6 or if we changed one to a 10 and we're going to get 10 plus however many other numbers there are so once again to emphasize this the rest operator here for the rest of the parameters should come at the end all of your other required ones should come at the beginning and this represents the rest which will be represented as an array inside of your function but not when you pass the parameters in you might also be wondering why I didn't assign the specific types to previous and if we Mouse over you can see previous is a number we Mouse over current it's also a number and if we Mouse over reduce we're going to get a bigger definition but you can see it returns a number as specified right there well we're already declaring what is being passed in and what will be returned from Total so typescript can easily infer that these should be numbers because we've already specified that above okay now that we have learned more about functions it's a good time to cover the never type which is a basic type but you don't see it that often and there are a few instances where you may need it but if you were not aware of it it would definitely surprise you so let's go ahead and create a function and I'll call this function create error and then inside of this I'm going to say error message and it's going to be a string and I'm not going to define the type here I'll just let typescript infer it is we're going to throw a new error and we'll just pass in our error message so now if I Mouse over create error we can see it Returns the never type and this is essentially for functions that explicitly throw errors so if we were to explicitly put the type here we could with never and it should look the same when we Mouse over and it sure does now it will also be a never type or a never return type from a function if that function has an infinite or endless loop inside so I'll just say const infinite I'll set this equal to a function that doesn't even accept any parameters here I'll say let I that's a number we'll assign one then I'm going to say while true inside the loop I'll just say I plus plus and now if I were to Mouse over infinite and look at the return type it's never because this is an endless loop we wouldn't want this so overall if you're having typescript help you and you look at what is being inferred and you see never make sure you want to throw an error if not you probably have a problem like an endless loop inside of your function so how could we solve this well let's go ahead and put an if I is greater than 100 and we'll just use a break so now let's see what the return type is for infinite now it's void there is no explicit return but that is much better than the never type where we would have created an endless loop so I'm not going to comment out this if statement because I do not want to leave an endless loop in your code however just remember that that's what this is about right here so it's currently as I'm going to leave it the return type is void but if this were not here and you had an endless loop it would be a never type so when could this never type actually be useful well let's look at how typescript thinks about things so I'm going to say const and create number or string and this is just going to be a function that identifies a number or a string so inside of here I'm going to have a parameter named value and it's a union type that could be a number or a string when it's passed in and we're going to return a string and I'll make this an arrow function now we'll say if type of value is string then we're going to return the word string and then also we can say if type of value equals number then let's just return the word number and now you would think that would be it because we can only pass in a number or a string according to what we have assigned here and we're always returning a string but typescript still does not like what we have defined so let's look at what's going on when I Mouse over it says the function lacks an ending return statement and the return type does not include undefined so how could we solve this in normal JavaScript just vanilla JavaScript we might just have an empty return but typescript is not like that either when we Mouse over it type undefined is not assignable to type string this function needs to return a string as we have specified here but what we can do is return our create error and we just pass in a message like this should never happen because it's essentially the never type and now typescript seems okay so when we Mouse over we've got a value number string and returning a string and typescript is great with all that because here we're returning a never type so essentially we've used type guards here to check the type of our value whether it is a string or number and we know this should never happen but essentially typescript needs That explicit return yet with the possible error when we do not have and we'll go ahead and remove this and look at the specific message it gave when we do not have an explicit return and it's not handling a potential undefined so I'll remove these comments and typescript should once again be happy but now if we're using these type guards like type of value is number or type of value is string many times in our code we might want to create a custom type guard for that so I'm going to Define it above and I'll just say const his number and I'll set this equal to a function that accepts a value and I'm going to set it equal to any here but we want a Boolean return type and now inside of the function I'm going to return type of and we'll have value equals number and I'm going to use a ternary statement here so if that is true will return true else will return false because that's what we need to return for this function it's a Boolean type so overall we're looking at whatever values passed in and if it's type of number true anything else is false so here instead of our type of value equally number we could just say his number value and have the same result so this created a custom type guard that we can use so I'll quickly annotate these this would be a use of the never type and up above we'll just call this a custom type guard and now we have covered functions literal types type aliases and of course the never type remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 18,969
Rating: undefined out of 5
Keywords: typescript functions | basics tutorial for beginners, typescript tutorial for beginners, typescript, typescript functions, typescript basics, typescript beginners, typescript functions tutorial, typescript basics tutorial, typescript beginners tutorial, typescript functions for beginners, typescript basics for beginners, beginners typescript, beginners typescript functions, beginners typescript basics, ts functions, ts basics, ts, typescript tutorial, js, typescript for beginners
Id: s7kyOtFF120
Channel Id: undefined
Length: 32min 12sec (1932 seconds)
Published: Tue Nov 01 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.