TypeScript Crash Course 2021 | The Basics From Scratch!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Saved this too. Man, you're working really hard for the community. Thanks for sharing :")

👍︎︎ 2 👤︎︎ u/JoyShaheb_ 📅︎︎ Feb 06 2021 🗫︎ replies

In this crash course, we're going to take a look at TypeScript. I'll teach you what it is and how you can use it in your next project.

TypeScript is a superset of JavaScript. That means that it can do everything that JavaScript can but adds more features.

The types that we'll cover are: string, number, boolean, array, object, any, void, null and undefined, tuple, enum, and generics.

👍︎︎ 1 👤︎︎ u/codeSTACKr 📅︎︎ Jan 29 2021 🗫︎ replies
Captions
[Music] in this crash course we're going to take a look at typescript i'll teach you what it is and how you can use it in your next project typescript is a superset of javascript and that means that it can do everything that javascript can but adds more features the main feature that it adds as its name implies is static typing in regular javascript you can create a variable of names and assign a string to it and then later on you can reassign a number value to that same variable javascript uses dynamic typing which basically means that you can assign anything to anything it's like the wild west so we need some rules to keep ourselves from making silly mistakes adding static typing helps us to catch bugs before we've even run our code and the amazing type checking that's built into the vs code helps us with this by using typescript we force ourselves to write cleaner code from the start now typescript cannot be read by the browser and so we will need to compile it to regular javascript before testing or deploying but that's really easy the first thing that we're going to do is set up our local environment to do this before we go any further you do need to know javascript first so arrow functions objects and array methods the dom classes etc if you aren't up to speed with those be sure to check out my javascript beginners course and javascript january series the links are in all of the places let's take a quick look at types types are not exclusive to javascript and they are common in other languages like c sharp and java the typescript types that we're going to cover are strings number boolean array object any void null and undefined tuple enum and generics let's get our environment set up for typescript first you'll need to install node.js if you haven't already we'll need this for its node package manager you can check if you have it by typing node v that will give us the version of node that's installed i currently have version 12.18.2 so next let's install typescript globally so we're going to say npm i for install g for global and then typescript next we're going to initialize typescript by typing in tsc dash dash init and that creates a ts config json file there are a ton of options here such as the javascript version by default it's set to es5 so you can also specify your root directory and output structure if you have a source folder and build folder for instance but that's for a more advanced setup so we're not going to cover those features in this video let's create some files we'll close this we're going to create an index.html and app.ts notice here that the extension is dot ts not js since typescript extends javascript we can write plain javascript in there and it will work just fine so we could say console.log and we'll say hi and this works just fine so let's go back to our html and just create a basic boilerplate here we'll say type script crash course and then let's add our script so that's going to be script with a source and that's going to be app.js and we're going to defer that notice here that this is dot js not ts browsers cannot read typescript files so we need to compile it down to javascript first so let's open up our terminal and we can run the command tsc which is typescript compiler this was installed when we installed typescript globally this command accepts two optional values we can tell it specifically which file that we want it to compile so we could say app.ts and then optionally what we want the compiled file to be named so we could say something else.js if we wanted but for this instance we only have one typescript file so we're just going to run tsc and now we can see that it created the app.js file and there's not going to be any differences here really we just have console log high console.log high let's go ahead and run this we'll open it with live server and then we'll open the console and we can see that it logs high so we just used plain javascript so let's go back into here and i'm just going to paste some typescript and don't worry about what this looks like you don't need to understand this right now you will understand it by the end of this video though so let's save this close the sidebar and now we'll need to run tsc again for it to recompile and then we go back to our app.js and we can see that it has recompiled this into regular javascript and notice that it's using var instead of let and that is because we were compiling it down to es5 standards so let's look at some basic types really quick like and subscribe it helps me out the first type that we'll look at is a string so we'll say a string equals hi now if we hover over this you can see that vs code is telling us that this is a type of string if we try to reassign a string to a number you'll see that vs code is yelling at us or typescript is it's telling us that a number is not assignable to type string so a string always has to be a string we could change this to another string and that will be just fine now if we need to initialize a variable and then assign a value later we have to explicitly declare the type first so to declare a type we use a colon and then the type which is string so now a string must be a string if we try to assign a number to it it's not going to let us but we can assign a string now alternatively we could do this we could say a string is going to be a type of string and it's going to equal string but this is kind of redundant and unnecessary so you really don't need to add this type here because it's implied when you assign it to a string right next we'll look at numbers so we'll say let a num equal 5. so again typescript has implicitly declared that this is a number and if we try to assign a number to a string it's not going to let us but we can assign it to another number and then again if we need to declare this before adding a value to it we would say a number is a number and then we could say a num equals a number all right the next type that we'll look at is a boolean so we'll say let a bull equal true and we hover over this we'll see that it is being assigned to a boolean type and so again if we try to assign anything else to this other than a boolean it's going to yell at us so add a number it's going to say that the number is not assignable to type boolean so we could change this to false and that will work just fine and again if we need to declare this first before assigning something to it we could just do like this add a type to it now if we were to just say let any var like this and we hover over that you'll see that it is of the type any so any undefined variable will default to this type of any if we say any var equals a string then it's going to default to the type of string but if we wanted this to be the type of any we could explicitly define that here and now it's of the type any and so we could go here and say any var is now equal to 5 and that's going to let us because this is of the type any it can be any type and this is really the default behavior of javascript so it really defeats the purpose of using typescript and i would try not to use the type of any if at all possible now there may be instances where you need a variable to be multiple types so let's say for instance let year and let's say our input is going to give us possibly a string or a number so we can say that year is a string or a number it can be either this is called a union and we use the pipe character to define the or so now we could say year equals 2021 and that's just fine we could also say year equals 2021 and that works as well but we couldn't say year equals false that's not allowed so maybe later on in our function it's has a const of parsed year and then it's going to equal parseint and then year and then we'll know that we'll always have a number here we can see that parsedint is now of type number all right next let's look at arrays and objects so first we'll say let array string equal and we'll just have a string in here so we have an array of strings and if we hover over this we can see that it is of the type string with square brackets so that would be just like saying string like this and so now if we want to reassign some variables within this we could say array string and let's take the first index if we say that it is equal to 1 that's not going to be allowed because it must be a type string we could reassign index 1 to another string and that would be just fine we could also try to push something into this string let's push a number that's not going to be allowed but we can push a string all right same thing with numbers so we can say let array number equal an array of numbers if we hover over that you can see that it is of the type number with square brackets so same as saying number square brackets and again if we try to reassign things say number raise 0 equals string that's not going to be allowed but another number is just fine and if we try to push a number that will be just fine but we can't push a string and then an array of boolean so we'll say let array bool equal say true and false all right so if we hover over this we'll see that it is an array of booleans with square brackets so the same as boolean square brackets right again typing this is redundant if you're assigning it but if you need to declare it first and then assign it later then you do need to declare the type so then again if we say array boolean index 0 equals a number that's not going to work string is not going to work but we can change it to false we can also do array boolean push and we can push another boolean and that will be just fine so now what if we want a mixed array that has strings numbers and booleans we can do that as well so we'll say let array mix equal 1 a and true so we can do that just fine we hover over this we'll see that it is a union basically of string number and boolean so if we were to declare this first without assigning variables to it we would say number boolean but because this is an array we have to wrap it in parentheses and then after the parentheses square brackets and i need to spell boolean correctly there we go so now this array can have any of these types within it so because of that it kind of defeats the purpose of typescript but so we can say array mix and we'll take the first index which is originally a number and we're now going to assign a string to it and it's going to let us so i don't really like that we can also array mix dot push we can push a string we can push a number we can push a boolean it doesn't matter any of these will work anywhere within this array so maybe you have arrays where that is necessary and that's just fine but that's something that we just need to be careful with so now what if we only want to allow certain types in specific spots of the array so let's call it a tuple so we're going to say let array2 equal a string and then a number so by default this is going to say that it is a union of string or number and that those can go anywhere but we want to explicitly define the spots within the array and what they should be so to do that we will have to say string and number so instead of defining on the outside of the array here we're defining inside the array right so we have the square brackets and then inside it we're going to say this first index 0 has to be a string and index one has to be a number right so now we go down here we can say array two equals and we can change the string to another string and we can change this number to another number and that's just fine now notice how i didn't have the number here i only had the string it's telling us that we need a string and a number we need both so we have to add a number in there now if i tried to do a number here that's not going to work it's going to tell us that we need a string and if i try to add a string here that's not going to work so it must be the other way around string and then number all right now let's look at objects so we're going to say let's person equal and this is going to be an object we'll say the name is jesse and age will say 25 sure why not so here we're implicitly defining the types within this object so we have a string here and we have a number and then on the object itself it is a name with string and an age with number so a per this person object must always have a name and an age and we'll see that right here so if we say person.name we could say equals another name we'll say john that will work just fine but if we try to say person.name is a number that's not going to work we need a string the same thing with age we also can't say person equals string or anything else because person has to be an object it needs to be an object with the name property and the age property and we also can't add on to this so we can't say person.email equals something because email does not exist in the type person all right next let's look at custom types so if you find yourself using a union over and over you have specific type that you want to reuse you can use something called type aliases so let's say let year string or number like we had earlier if you're using the string and number union frequently we can create its own custom type so we can say type we'll say string or num equals string or number and now we can use this custom type here to define our year of course then we could say year equals 2021 or we could say year equals a string 2021. so now you can reuse this type anywhere else in your code to define something as a string or number all right next let's look at functions so we'll say function let's say calc sum and it's going to be past two values and then we're just going to return a plus b all right this is a very simple javascript function this will work just fine in regular javascript and we could call calc sum and we'll say 2 and 2 and so that would return 4. you can see the typescript is kind of yelling at us it's assigning any to these and it doesn't like that so it wants us to do something here so what we'll do here is we're going to define a is going to be a number and b is going to be a number and so now if we tried to pass anything other than a number it's going to yell at us it says the string is not assignable to parameter of type number so it must be a number and now if we hover over this we can see that we have a as a number b is a number and then notice at the end of the function there it has another colon number so that means it's going to return a number so it'd be the same as typing colon number here so we're explicitly saying here that this function is going to return a number but again we don't have to type this because typescript is inferring that it's going to return a number because of our return statement here and the fact that it's passing in numbers but what if we want to make sure that a function functions as intended we should declare that function first before we write it so this time i'm going to rewrite this function as an arrow function i'm going to say let calc sum and i'm just going to define the types so we'll say a number and b number and then arrow and we're going to return a number okay so we're just defining this this is a function it's going to accept two parameters that are numbers and it's going to return a number so since we've defined this now when we actually write the function it's going to ensure that we write it correctly so we'll say calc sum equals and we'll say first that's going to be a number second a number and we're going to return first plus second okay so that works just fine now these don't have to match a b you can put whatever you want here and then you can name them here when you're actually defining the function so now because i have this defined up here if for some reason i forgot to return then it's going to yell at us and it's going to say that it's returning a type of void and it should return type of number so we'll get to void in a minute but we need to return this number for it to function properly now sometimes in functions you have optional parameters so we could also say that we have a third parameter and that is going to be a number now if we go down here and we actually call calc sum we pass it 2 and 2 it's going to yell at us because it's expecting a third number third is not provided so if this parameter is optional we can just add a question mark before the colon and now we can pass two or three values and always be sure to have your optional parameters at the end of your function you can't have an optional first because the first value needs to be there really quick like and subscribe it helps me out okay so earlier we saw that void is a type so let's look at this we'll say const say hi equals an arrow function and we're just going to console log i okay so this function returns void so void is nothing it's not undefined it's not null it's just a complete lack of anything and moving on we'll look at interfaces so interfaces enforce a certain structure of an object so we're going to say interface now this is going to look very new so we're going to say person interface and we're going to say name it's going to be a string and age is going to be a number okay so this this defines a person object and what it should look like so very similar to earlier we had a person and the person had a name and an age this just defines what that person object needs to have within it before we actually assign any values to it okay so in order to use this we can say let mike and mike let's see let's just say equals an object for now we're going to say name mic and then age is going to be 34. okay so if we hover over this we can see that mike is an object just a normal object and this looks just fine but we want to make sure that mic adheres to the person interface that has all of the types from the person interface so we can do that explicitly here after mic we say mic is actually not an object technically it is a person interface so now if we hover over this we say mic person interface and now if we changed this here to a number that would yell at us because it's expecting a number we took this back off we can see that it's just fine because we're declaring that here mike has a name that is a string and age that is a string because we're defining it here but instead of defining it here we want to define it here so that we do it correctly so now we know that this needs to be a number and not string and we can use interfaces on classes as well so let's look at a class we'll get rid of this we'll say we'll say class of person and we're going to say implements person interface so we need to have a name that is a string and an age that is a number and in classes we have to have a constructor so we'll say name is a string and age is a number then we'll say this dot name equals n and this dot age equals a all right so this all functions properly as a class should so we're defining name and age and then we're taking our constructor again this n and this a this you could put whatever you want here as long as you assign them to the proper values down here so this dot name is referring to the person name we're assigning it to the name string and then this dot age equals the age string right and all of this is working together to make sure that it functions properly if we try to add something else let's say email and that is a string that's not going to work because this needs to adhere to the person interface which only has a name and an age so we could also add a method onto this class we're going to say greet and then in here we're going to return we'll say hi my name is and then we'll add this dot name and i am and then this dot age so now in order to use this we could say let john equal a new person we're going to say that his name is john and his age is 35 and then we can console log john dot greet we see now that we don't have any red squigglies anywhere so it's very likely that our code is going to work just fine when we run it let's go ahead and run this actually we're going to save that now we need to recompile it so we're going to go back and into our terminal tsc recompile and then let's go back to our website alright so we can see here it says hi my name is john and i am 35 and this error has nothing to do with typescript so another cool thing about classes is the ability to add access modifiers so we can say that certain values or methods are private public protected or read-only so for instance right now on john we could say what is john's age name or we can call the greet method if we go up here we could actually say that name is private and now if we go down here to john and we check we can now no longer access name outside of the class now within this method greet it can still access the name but that's because it's still inside the class so that's pretty cool we can also rewrite this to be a bit cleaner so let's get rid of this we're going to say constructor we're actually going to get rid of the assignment as well so we're going to say constructor now we have to use the access modifiers for this to work so we're going to say public name is a string and we're going to say public age is a number and that's all that we actually have to do it's going to automatically assign these values because we declared these just like this with the access modifiers the name and this type so this looks a lot cleaner and again now we can call age name or greet so next let's look at dom and type casting so we're going to implement what we've written so far into our html so that we can interact with the dom so in the body we're just going to write some simple html here we're going to add a form it's not going to have an action inside the form we're going to have an input and it's going to have a name of name and then id of name we'll have an input that is a number and that's going to say age and age as the id and then another input that is going to be a submit and we'll say say hi now after the form we're going to have a div with a class of greeting whoops greeting just like that all right that's all of the html we're not going to add any css and style this this is just an example so now we need to get our inputs so we're going to say const input name is going to equal document.queryselector and we're going to get the id of name now if we hover over this typescript is going to tell us that this is a type of element or null so it knows that it is some type of document element but it doesn't actually know if the element exists it doesn't have access to the html file so that's going to come into play a little bit later just remember that it could be null but it is of type elements so if we go down here and we say input name and we want to get the value of the input so val u and we can see that it's not popping up as a selector here so intellisense isn't really working that well right now because it doesn't actually know that it's an input so if we go up here and we change this from the id of name to an input and now we hover over it we can see that it is of type html input element so that's what we want it to be so now let's change this back to name as we're going to say html input element so now if we hover over this we can see html input element that's the proper type and now if we try to get the value we can see intellisense is helping us out and we can actually select the value we see how when we set this up properly and we declare things properly intellisense is going to help us out and it's just going to make our development lives so much easier so let's get the input age now so we'll say input age is going to equal document.queryselector and that was age and this is also going to be an html input element all right we also need to get the form so we'll say input form because we need to know when the form is being submitted so we'll say document.queryselector and then that was a form and now because this is just a form tag typescript knows that this is an html form element so we don't have to typecast it again i think i forgot to mention this is called typecasting and then the last thing that we need to get is the greeting div so we'll say greeting going to equal document.queries and then that was a class of greeting okay so now this is going to see this as an element but we do need it to know that it's a div element we're going to leave it like this for now and we're going to come back to it and fix it later because i want you to see why we need to typecast this as a div element so now instead of getting or setting the person element manually we're going to get that from the form so we need to add an event listener on the forum so we're going to say input form dot add event listener and we're going to listen for the submit event and then we're going to have an arrow function all right so now it has this like question mark dot event listener because it's not quite sure if this form is actually there so it's kind of doing a little check to see if the form is there if we got rid of that then we're going to get this little squiggly saying that it's possibly null we don't actually know if it's there so in order to fix that we could again add that question mark here or we could go up here and on this form at the end we can add an exclamation mark so that's going to tell typescript that this form is actually there you don't have to worry about it so now on submit we want to get the input values and then use the class to return our greeting string and then we're going to display that string on the page so back in our event listener we do need to get our event because we need to say e dot prevent default because we don't want when we submit the form the default behavior is for the page to refresh and we want to prevent that page refresh so now we're going to get a const of person and say equal to a new person and we're going to add the input name dot value and the input age dot value now you would think that input age dot value would be a number right because if we go back to html the input type is number if we go back here and we hover over this we're going to see that it is actually a string and that is true the input is of the type number but it actually returns a string with a number in it so for this instance instead of value we need value as number and that will clear up all of the issues all right so now we need to add this greeting so we're going to call this greeting method we're going to add that into our greeting html element so we're going to say greeting dot inner text and notice here that it doesn't find inner text and that is because remember we said we needed to know that this is a div element so if we change this out to a div and then hover over this we can see that it is html div element is the proper type all right so let's undo that we're going to say as html div element and now when we go down here we can see inner text is an option now so now inner text is going to equal person dot greet all right and then the last thing that we're going to do is we're going to say input form and put form dot reset okay so we just want to reset and clear out the input values whenever we submit so that should be it we don't have any red squigglies and now one last thing that i want to show you is again we need to run tsc again to recompile this but let's say that you're working on typescript a lot and you don't want to keep hitting tsc every single time you hit you save and you want to test something so we can actually say tsc w and that's going to watch all of our typescript files and automatically recompile them every time we hit save all right so we'll hit watch and now if we go up here and we hit save again you can see that it has recompiled again so let's go back to our website okay so we have two inputs we can have our name and we have our age so we'll say name and age and then we can click say hi and we get hi my name is jesse and i am 35 it clears the form we can fill it in again we can say mary it's 25 and now we get that so it's working perfectly all right next we're going to look at generic so sometimes there may be instances when you don't know exactly what type something might be and so we're going to look at a generic in a function first so we'll say function do something and that's going to have an argument here and then we're just going to you know do something and then return our argument so this is a normal function that would work just fine now it wants us to tell it what kind of um argument this is so let's say we we call do something and we're going to pass it a string right maybe sometimes we might pass it a number you know we're not quite sure what we're going to pass it so we can't really define what it is here so to do that we're going to say e and then we're going to say the argument is t so this can be anything you could say x you can you can put whatever you want here generally you're going to see an uppercase t here but basically this is a placeholder so whatever we pass into this placeholder is going to get pushed on to the type here and we can even say that we're going to return t right we can do all of this if we hover over this it's going to show us exactly that and now when we pass a number in here it's working just fine we pass a string it's going to work just fine as well because it's going to say that it is a string so if we hover over this we can see that a string is being passed into all of those types if we change this back to a number now a number is being passed now we can specifically say that here as well we could say string needs to be passed but we're passing a number so that's going to fail so we change this into a string now it passes we can also use this with interfaces so let's go down here we could say interface book and the book needs to have an id which is going to be a number and it needs to have a name which is going to be a string and it needs to have some data which we're not quite sure what the data is going to be it could be lots of different things so in order to pass this option up here on book again we're going to say t and then we can pass this t here as the type so then when we go down we can say const a book is going to be a book and it's going to equal an id of 1 name is going to be title 1 and then data is going to be let's say it's a string this time so more data here so we need to tell it that this is a string so we'll say right here we're going to say string and that's just fine so it takes this string and it passes it here and it puts the string type into this data so it knows that we're going to have a string here if we change this to a number that's not obviously not going to work it needs to be a string and let's say we have another one let's say a const b book is going to be book and we're going to pass something here in just a minute equals we'll say id is 2 name is going to be title 2 and then data this time the data needs to be an array of strings so we're going to say array maybe this is a review one and then review two right so in here we're going to tell it what that type is by saying string array and that will work just fine so both of these this one is a book with a string a single string and that's working but this one has an array of strings and it's working as well all right next up we're going to look at enums enums are a way to assign a descriptive word to a numeric value so a lot of times in a database you might see something has a type of two or a type of three and you're not sure what that type is you have to go find the type table and figure out what is this type so in order to demonstrate that let's write something out here so let's say we have a const of my car and that is going to equal an object we'll say the year is 2021 and the make is going to be 3. so this is something you'll commonly find in a database the make is 3. what does that 3 stand for so to make things easier we can declare an enum we're going to go up here and we're going to say enum and we'll say manufacturer make that is going to equal an object we're going to say we're going to put a list of manufacturers in here so we'll say tesla audi mercedes volvo and bmw oops didn't mean to put the equal sign there no equal sign enum manufacturer make and then the object so within this think of these as indexes so index 0 is going to be tesla 1 audi 2 mercedes 3 volvo and 4 bmw so now instead of having to remember okay 3 is supposed to be volvo right i can just say manufacturer make dot volvo and this is going to actually put in here the number three and we can see that let's do a console log so we're going to say my car dot make and we're going to get that in our console so let's save that and remember we still have the watcher running so all i have to do is go back to my site let's open up the console again and we can see the number three so that is the basics of typescript you can use it just about anywhere that javascript is used such as in angular react view node.js so in future videos we'll look at incorporating typescript with these other technologies as well so i hope this helped that's going to be it for this video like this video to help me out and subscribe if you haven't already for more videos like this [Music] you
Info
Channel: codeSTACKr
Views: 19,491
Rating: undefined out of 5
Keywords: typescript, learn typescript, typescript 2020, typescript course, typescript for beginners, learn javascript, typescript full tutorial, typescript vs javascript, typescript getting started, webdev, app development, javascript, js, ts, strong type, typescript tutorial, ts tutorial, type script, esnext, angular, typescript 2021, typescript tutorial for beginners, typescript crash course, typescript basics, web development 2021, typescript tutorial 2020, typescript tutorial 2021
Id: wyO8RWl1ges
Channel Id: undefined
Length: 42min 18sec (2538 seconds)
Published: Fri Jan 29 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.