Practical TypeScript – Course for Beginners

freeCodeCamp.org · Beginner ·🌐 Frontend Engineering ·2y ago

Key Takeaways

This video course covers the basics to advanced concepts of TypeScript, including type annotations, generics, data fetching, and the Zod library, with practical challenges for real-world application.

Full Transcript

John smilga teaches this course about the Practical applications of typescript typescript is a strongly typed programming language that builds on JavaScript this is an excellent course for people who want to learn typescript hey what's up it's John from coding anic and welcome to practical typescript course we all focus on practical applications of typescript so you can start using it effectively in your projects right away during the course we'll cover everything from setting up your development environment to deploying your typescript applications the course consists of three major parts first part typescript fundamentals where we'll explore basic types interfaces classes generics and rest of the good stuff second part react and typescript where we'll integrate typescript into react projects create typed components and manage state with typescript and the third part is where we'll put our typescript knowledge to good use and build a modern store application with typescript shat UI and react router if you wish to explore all of the features of the store project it's located at this URL typescript comy sloth ny. apppp again the URL is typescript comy sloth ny. apppp quick sign not during this video will only cover Parts one and two so if you enjoy the content and wish to work on the big project as well consider enrolling in the full Course located at coding addict IO again the full course is available at coding addict IO okay and first let's recap that JavaScript is considered Loosely or dynamically typed because variable types are determined at runtime and can change as the program executes this means you don't have to declare the type of the variable when you create and variable can hold values of different types at different times so the following code is a valid JavaScript code however where are we going to encounter an error if we try to run this code correct at runtime and this is manageable if you have few lines of code but the bigger the project the more challenging it will be to spot such technically innocent bugs and this is where typescript enters the picture because it is a programming language that builds on JavaScript by adding static typing this means you can specify things like types of variables function parameters return values and some other things to help catch errors early and improve the code quality it is a super set of JavaScript so yes all the JavaScript code is also a valid typescript code now one way to think about it is as follows by using typescript in our project we'll still write the JavaScript we already know but with some elements or sprinkles of typescript and these elements will act as safeguards or constraints to help us catch potential errors more quickly and without the need for 10,000 console logs when we introduce typescript to our project we will write our app in the TS or in the case of react in the DSX file there will be a compile or transpile step where all of the typescript code is transpiled to good old JavaScript code and at the end since it is a vanilla JavaScript code we can run it anywhere quite often you'll hear people say something along the lines of well once I built my first project with typescript it was very hard to go back and build with just vanilla JS and even though I was also very skeptical of such statements I can verify that it was the same in my case yes typescript still has learning curve and yes it involves more work but at the same time you'll notice how how you're able to fix bunch of the errors quickly at build time without running around like a headless chicken before we set up a brand new typescript project I want to mention a few useful things if you're confused about some topic or simply want to research a concept in more detail a good place to start is typescript docs which are located at typescript l.org again the URL is typescript l.org also in there under the playground tab you will find a Nifty code sandbox or typescript playground which I might utilize from time to time during the course to underscore some particular point it works as follows on the left side we write a valid typescript code and we get back the resulting JavaScript code now you won't be able to build the entire project in there but it is a very cool option if you you quickly want to test something as far as the code editor I'm going to use VSS code and since it's practically an industry standard these days my assumption is that you'll use the same one since I record courses I use the very basic default theme and when it comes to my extensions I will mention some useful ones once there is a need during the course in order to work with typescript you will need no installed on your machine again something I assume you already have done but if it's not the case please visit nodejs.org again the URL is nodejs.org pick your operating system and follow the install steps also during the course I'm going to reference the main course repo where you'll find source code challenges notes useful references and tons of other useful stuff so I highly suggest getting a hold of the repo before you continue with the videos just look for my GitHub profile and under the repos search for typescript course repository there are few ways how we can add typescript to our project since it's available as an npm package we can install it globally or on the per project basis set up the configuration and run the compile step manually the this is definitely an option but we're going to take a different approach which is going to be pre-built template because at this point at least in my opinion it's a more realistic scenario chances are whether you want to build a nextjs or remix or a good old react app there will be already a template that contains the technology you want to use as well as types configuration so more often than not your job will be to write a valid code instead of losing your sleep over correct configuration setup for this course I picked V since it's one of the most popular build tools out there but please keep in mind as far as the typescript logic is concerned it's the same if for example you're going to use nextjs with a typescript template now we want to run one command in order to set up our template and I'll show you two places where you can get the command First Option you can navigate to V docs which are located at bejs dodev then click on getting started and pretty much you're looking for this command and then we just need to pick the template and since my npm version is bigger than seven I'm going to run my command with the Double Dash now as you can see we have tons of templates available and the idea is following we go with npm create V latest then project name then Double Dash go with the template one and pick the template as you can see we can go with reacts as a say not something we're going to use in the part two and three we can also for example set up The View with typescript and we're actually going to start the course with vanilla typescript template so this is just going to be an application built with vanilla JavaScript we're not going to use react and uh to tell you honestly we don't really care about the template we just want to use it in order to learn typescript so pretty much most of the first part of the course will spend in one file and you'll see what I'm talking about in a second now remember in the previous video I mentioned the main course repo navigate over here and then look for typescript tutorial and under this directory look for read me and here you'll right away get the command and as a this is something that I'm going to copy in literally a few minutes and I suggest actually doing the same because in here again you'll find find all of the notes and challenges and all that cool stuff so if you want to save yourself time on typing just navigate over here and grab the command again npm create V at latest then at least in my case the project name is going to be typescript then double dashes then template and we're going to go with vanilla DS so let me grab the command let me navigate I guess to desktop and and I'm going to zoom in then let me set up my command and once I have successfully installed the project on my machine I want to open up my text error drag and drop the folder and next we'll take a look at the files and folders available in this template as far as the files and folders we've got over here a public one so this is where we can place the public assets then we have a S one essentially this is where we'll do all of our work a get ignore where we specify which files are going to be ignored by The Source control then index HTML which is actually going to be our homepage also a package Json something we're going to cover in more detail in a few minutes and also a TS config which we'll cover in Greater detail later on in the course and before we take a look at the specific files and cover the build step here are a few things I want to do first since it's a node application we do want to install the dependencies so effectively just open up the integrated terminal and run npm install now also again I highly suggest getting the readme since in my opinion you will find find it super useful as you're following along so just navigate back to the project and somewhere create a read me markdown one and just paste the contents over here save it and once we install dependencies now we also get the node modules so this is where all of our dependencies are located then we want to go with npm run Tav which is going to spin up our project in local development and we're looking for Local Host 5173 and this is what we should see on the screen so essentially there's some images over here a text as well as the counter now if I'm being perfectly honest like I mentioned previously we really don't care about the actual vanilla JS application I believe towards the end of the first part of the course yes we will build a tiny app but most of our time we'll spend over here in a source one in one specific file called tutorial DS where effectively we will just learn all the typescript fundamentals now if we take a look at the package Json we see that we have the dev one this is the command we just invoked and also there's a build one now before we run build I do want to create a file and showcase how our setup is going to look like now one interesting thing that I do want to point out notice how before the build command they actually invoke tsnc so notice how typescript is a Dev dependency so before the project is built first it's compiled so that's the step I mentioned previously where we're going to write all of our code in the files with Ds extension and once we perform the build step it's going to spit out the vanilla JavaScript code so if we take a look at the index HTML like I said this will be our homepage so for example if you want to change the title it's definitely an option then they have over here this div with an ID of app and effectively in a second you'll see how in the main DS they in Jack the images the divs and all that into this app one so now let's navigate to the main DS in here they import styles again something we're not really concerned with also two images the typescript one and V1 and also a counter and then they select div with an ID of app and like I said they dynamically inject the elements into the d as you can see there are some already sprinkles of typescript and essentially this is something that we're going to cover during the first part of the course but most of the logic should look very familiar correct because this is straight up JavaScript again with just sprinkles of typescript now if we take a look at the counter it's going to be same idea this is straight up JavaScript with the only difference that now we're looking for element and actually we specifically say that the type is going to be HTML button element now how is our setup going to look like since I said that I mean we really don't care about this code and to tell you honestly we're not actually going to look too much in a browser either most of the time will spend in the error well in here in the source I want to create a new file in my case I'm going to call this tutorial TS the name is totally up to you just make sure that you add the TS extension so we're going to go over here with tutorial then TS we create a new file and for now I just want to log just so I can see that everything works and I'm going to go with typescript and then tutorial let me save it and then in order for this code to run we just want to navigate to Main TS and we just want to import a file that's it we're not going to do anything else we'll simply go with import and now we're just looking for our TS file so tutorial and TS and the moment we do that once we navigate to the browser if everything is correct we should see that console log and if that's the case we are in good shape and before we move on to typescript fundamentals let me show you the result of the build step again let's just recall that before V our build tool builds the production ready application it's actually going to compile our code which essentially just means that all of the typescript elements we're going to have in our code are going to be transpiled to good old vanilla JavaScript and essentially during this video I just want to showcase that so don't worry about the code I'm going to write in fact you don't have to follow along I just want to showcase the end result so let's say if we're going to add something typescript for example interface of course something we're going to cover during the first part of the course and I'm going to go with name String and ID number and as a sign note essentially it's just a shape of an object and then I'm going to create the object and I'm going to go with some value so add the type over here and now I just need to provide name which has to be a string now so I'm just going to go with random and comma and then we're going to go with ID and then one two 3 and then let's also log so let's go with some object so once we navigate right now to a terminal we have few options if you want you can always stop the dev server and essentially you do that with contrl C or you can just open up a new terminal window and that is going to be my Approach so essentially now I want to go with npm and not Dev but we're actually looking for build so we run this command if we don't have any typescript errors we're going to be successful and now notice we have this this folder so this is our production ready application we still have index HTML okay everything is beautiful and then in the assets we'll have the index JS so this is essentially our application in vanilla JS and if we take a look at our code so notice I have this console log typescript tutorial so I clearly know that it's coming from our file notice there is no interface anymore again there is some kind of minified object over here and effectively we also conso log it that's it so there is no interface there is no type string or type number or in fact any of the other stuff that we have here as far as the typescript elements so again essentially we'll write all of our logic in files with Ds or DSX extension if we're working with react and then once we build our project we're going to get back our good old vanilla JavaScript code which essentially we can run anywhere so hopefully it's clear what's happening during the build process so now let me clean up our project first I want to remove the disc folder then also I'm going to remove my second terminal window and at the very end I just want to remove this code from tutorial yes so this is going to be our starting point essentially we have console log in tutorial DS and if we take a look at the browser we should see over here typescript tutorial and if you have the same result now we can move on to the next task okay and let's start our typescript journey by discussing type annotations which allow us to specify the variable type so let's say in my project I have a variable by the name of awesome name and if you have watched any of my courses and tutorials you know that the most awesome name ever is shake and B since I'm working in a typescript project I can actually explicitly set up the type and the syntax is following we go with colon and then since I want this to be a string I type string now there are quite a few types and I'm not going to list all of them I really find it pointless essentially the most straightforward ones are string number and Boolean and again the syntax is going to be the same so we just go over here with the colon and then the type and of course as we're working through the course we'll get to know the other types as well and the moment I set this type for my variable I get two things out of the box essentially it can never be something something else so I can go to the next line and set it equal to a function and also I'll WR way get the methods that are associated with this type so in this case it's going to be a string so just to demonstrate that if I go to the next line and if I set it equal to a value of something this is still valid why well because type is string so everything's correct correct also I can go to next line and set it equal to awesome Dot and notice right away I get only the methods that are associated with the typ string which again is super awesome because essentially I avoid some unnecessary bugs so in this case I'm just going to go to application and now if I log this value if I go with awesome name and take a look at my console if everything is correct should be equal to a something so we set it equal to different string value and then we ran the two uppercase method now one thing we canot do is something like this where I go with awesome name and set it equal to 20 which is a different type so notice immediately typescript starts yelling at me type number is not assignable to a type string and I want to repeat the same thing for the number as well as the bullion so just so it's clear we're going to start with some kind of variable in my case I'm going to go with amount I'll set it equal to a number and again I can do anything that's allowed with the numbers for example and set equal amount 12 minus 1 something like that but cannot set amount equal to pens that's not going to work right away typescript is going to be super helpful it's going to say Hey listen you said this is going to be the number so yeah you can run the number methods you can do calculations but you cannot just reassign it to something else lastly let's take a look at the Boolean pretty much same deal we're going to go with is awesome we're going to add a colon set up a Boolean type for Star it's going to be true then we're going to set is awesome equal to false and then let's try to set it equal to shake and bake again the most awesome name ever so we're going to go with is awesome and let's go with shake and bake again cannot do it because the type is bulling and essentially in the process we're just avoiding this entire debacle where initially it can be one value then three lines later it's something else and then we're turning into a third thing and then start running some methods on it essentially this is static so now we say Hey listen this is going to be string and string only same goes for number Boolean and in the process we just avoid bunch of unnecessary bugs that come from typos that come from just using wrong methods and that sort of thing and before we work on our first challenge let me quickly mention something typescript is actually really smart and can infer the type of the variable based on the values when it's defined now the fancy name is type inference but essentially for us it just means that we can remove all of these type annotations and we'll still get all of the goodies that I covered in a previous video so now if I hover over the awesome name notice how based on the value when the variable was defined typescript can nicely infer the type so in this case it's string then it's the amount and then when it comes to is awesome typescript knows that it's a Boolean now don't dismiss the type annotations we're still going to use them but most likely not for such straightforward variables type inference also has some gotas especially when we start working with more complex values so yes typescript is always going to try to help you when it comes to functions when it comes to variables it will try to kind of get the type based on the value and obviously it's super awesome because it saves us time notice I don't have to go to Every variable and just make sure that the type is set but there are some questiones we need to aware of and don't dismiss type annotations because we're still going to use them throughout the course just not four variables like this okay and now it's time for our Challenge and since it's our first one I will cover the steps as well but with the future challenges just so we can save little bit of time I will most likely right away start working on the solution also since it's our first one it's going to be extremely straightforward I just wanted to get the ball rolling just so we get used to this idea that we learn some stuff and then we work on some kind of challenge so I want you to create a variable of type string and try to invoke a string method on it then same is going to be with a number create a variable and try to perform a math operation also I want you to create the Boolean one and perform The Logical operation and then try to just assign some values to those variables that are different types so just try to come up with something that shouldn't supposed to work and see whether typescript complains about it now you can use the type adaptation or you can also use the type inference that's totally up to you again super straightforward challenge where just want to navigate to tutorial I want to come up with some kind of variable for my string in my case I will use the type annotation don't ask me why just think that it's going to be better in this case so I'm going to go with hello and then let's go with typescript okay beautiful then let's run the two oper case so greeting is equal to greeting dot then two uppercase let's invoke this this should work we should have no issues and as long as I don't have the red squiggly lines I'm good to go so typescript is not yelling at me then also let me set up the age so in this case it's going to be a number I'm going to set it equal to 25 then let me add a five to it okay also works everything is beautiful and then we want to go with is adult so that's my Boolean let's add a type annotation here AG is let's say bigger or equal to 18 now this should be true and you know this is the case where I will log it so let's see is adult is true yep that's the one so now let me just set it equal to the opposite I'm going to go with his adult is equal to opposite is adult again let's log it and now it's going to be false and and then somewhere here let me just try to set the greeing equal to 10 that shouldn't work also we can go with age and set it equal to 30 so string again we're going to get the error and lastly we have the is adult and I'm just going to set it equal to yes and as you can see all of them result in errors so again we have one type and typescript is not happy when we just randomly decide that our variable is going to be of different type all right and before we continue with tutorial let me show you something interesting about the setup you see even though we have these typescript errors over here we're going to be able to run our project locally so what am I talking about well if I go here and set up the console and log and in my case I'm just going to look for all three values So reading age and is adult if we navigate to a console you can see first of all that all of the variables have the values that they're not supposed to so typescript is complaining but it's still works and also notice how our project didn't crash we're just getting these typescript errors correct so here's the deal when we're working with typescript actually project is going to work even with the errors locally but whenever we want to host a project what do we need to do well we need to build it that's usually the setup and in order to build it we'll have to pass the typescript checks so if we try to build with typescript errors we're going to fail and as a result we won't be able to host the project let me show you the package Json notice over here so we have Dev command which essentially just spins up the dev server and we also have the build command and remember before we even run feed build we actually compile this with typescript and again if we have some errors we won't get the I believe it was this folder where we have the static assets which in turn are going to be used to host our project so let me showcase that just so we are on the same page first I want to stop the dev server let me run npm run build so at the moment I have the errors typescript errors and immediately I just get back these error messages in my console so in order to fix it what do we need to do well in this case it's sort of simple where can just comment them out delete them whatever doesn't really matter again let me clear everything here let me run the last one npm run build and now since I don't have any typescript errors notice I have the this folder and this is where I have my production ready application so again locally even with typescript errors you'll be able to run the project however you have some issues once it's time to to deploy it once it's time to build the production ready application and up next let me introduce you to a union type which allows a variable to hold a value of multiple distinct types for now we're just going to take a look at some basic examples but since Union types are super powerful it's not the only time you'll see them in the course so once we start working with functions or and all that yep we're going to use the union type as well so let's imagine I have a variable by the name of tax and typically it's a number correct so I can set it equal to 10 typescript can nicely infer the type and I'm good to go but let's imagine that whether I'm getting it from the API or whether user provides that value it can also be a string I can go here set up my colon then go with number so it will definitely be a number and I can use this pipe operator and then I can just add another type which in my case is going to be string now please keep in mind you can add 10 another types but I mean in our case we're just going to stick with two but yeah you can go here and add for example Boolean it's definitely an OP option so now I can go to a next line and I can set it equal to a 100 and typescript is not going to complain because yeah one of the types is actually number now I can also go here and set it equal to a string and in my case I'm going to go with uh let's go with $10 over here so both of them are valid because now I have Union type where it can be either a number or a string now once we start working with more complex examples yes we'll have to do some checks and all that so all of that is coming up but this is a super powerful concept where essentially we can say to typescript hey this is going to be either this or it's going to be the another type now also something that I was blown away is the fact that we can set up the literal value type so that's the fancy name essentially it just means that I can provide the literal values let's imagine we have a request status so that's my variable now what are the typical values for the request status well quite often it's pending success and error so for starters I can just go here with pending so that will be my initial value then go with the colon and now I can just provide the potential string values which are going to be pending then again I use the pipe operator I provide success then another pipe and I'm going to go with error and what's super super cool is the fact that whenever I work with this request status notice I right away get these suggestions so it can either be error pending or success and again it helps me to avoid errors because it's way harder to mistype something and also I kind of just go here and say random I mean first of all it doesn't match my suggestions and second right away typescript is going to complain so I don't have to find doubt about this bug in the runtime I actually can see it right away as I'm building the project so let me go here with success error is going to work so there's nothing wrong with that but if I'll try to set it equal to random as you just saw I mean typescript is not going to be happy about it topic we're going to come back to when we set up more complex examples and again Union types allow us to set up multiple types for the same variable and while we're still in a roll let's also cover type any which allows us to opt out of the type checking so I'm going to create a variable and I'm going to name it not sure so not sure now I will set it equal to four and since we already covered that typescript can infert a Type we'll see over here this number but I can also go with colon and set up any over here now any means exactly what the name implies this going to be anything I can set it up equal to function string Boolean whatever so in next line can say you know what not sure is actually going to be a string maybe a string instead then on next line I can set it equal to false and as you can see that script is not complaining now as you're looking at it probably the first thought is well wait a minute that's how variables behave in JavaScript and you're absolutely absolutely correct now as with everything in programming there's bunch of fights over it whether you should use any at all as far as my two sents be very careful when you introduce any to your application because it can spread like wildfire so you started off with setting up one variable type any and then next thing you know you have any all over your application because for example when you return any from the function then the result is any and on and on and on and on so definitely have a good reason why you want to use any and as I note any is something you'll see quite often when typescript is trying to come up with a type but we haven't provided any clues for example if I'm just going to go with some random and I'm not going to set up the value as you hover over it notice now this is going to be type any so this is something we quite often get by default when typescript is trying to get the type but I mean I haven't provided any clues what this value is going to be and this is essentially something that we'll constantly try to fix where for example for functions implicitly it starts with any but we don't want it to be any we want it to be some kind of type so just be careful when you use it it's definitely an option it's useful if let's say you want to test something it's also useful if you have a pretty big codebase and you just slowly want to introduce typescript so you still want to run the project but you slowly want to add it to your project yeah it's definitely the case just again be very mindful when you set something any because next thing you know it half of the application is going to be any and then at that point I mean it kind of loses the sense to use the typescript in the first place again those are just my two scents if you go to Google you'll find definitely way stronger opinions but let's just leave it at that and let's move on to the next topic and next let's see a practical application of type annotation where essentially I have a list of books so I just have some strings over here and I also have a variable which at the moment is undefined and there's no type since again I want to showcase what type is going to be set by default and I want to set up a loop where I iterate over and then if it matches one of these titles over here then I'll set the variable Found book equal to that title so first let's set up the loop I'm going to go with four off Loop so lead book off books then we're going to set up the condition so if book and I think I'm going to go with the first string over here so I'm going to go with 1984 if that's the case then phone book is going to be equal to a book and we're also going to break out so let's add the break keyword let's save it if everything is correct this should be equal to a title so we can actually go with log and then found book let's take a look at the console yep we are good to go now everything is awesome but let's take a look at the type we have over here by default it's actually set to any which leads to problems because anywhere whether that is in the loop or over here I can do something like this I can set it actually equal to 10 so typescript is not stopping me and this is the behavior which I don't want because I actually want it to be a string otherwise yeah in here it's going to be a string if I'm successful inside of this Loop but then eventually it might turn into a function again good old JavaScript variable Behavior but I don't want this I want this to be a typescript project where I explicitly know what is the type so what's the solution well we can navigate back over here and and we can set it equal to a string but now we have another problem so let me remove these console logs how do we know that for sure it's going to be a string because keep in mind this runs when at runtime so if let's say I set it equal to 1983 well this Found book is not going to be equal to a book what is it going to be equal to well remember by default variable are what undefined so if you'll try to set up some kind of logic over here assuming that it's a string typescript is going to yell at you it's going to say Hey listen you are using it before there's even any kind of value because again typescript is not going to check whether at the runtime this will be equal to a book so yeah we can set up the logic over here where I can say if for sure the Found book is equal to a book typescript knows that actually these are strings so we can run the method on it for example again let's go with length so this is going to work but we cannot do it outside of the loop because in here there's no guarantee that actually this will be a string so we need to set up the union type where I'm going to go with okay it potentially could be a string but by default actually it is undefined so it's another type that we can use so now by default it's going to be undefined if we're successful it's going to be equal to a string and what's super super super awesome is the fact that typescript is going to be extremely helpful where if you try to again go with the good old length notice how it will immediately add this optional chaining why well because it can be undefined and we can see that if we take a look at the error message if you just added dot notice Found book possibly can be undefined and therefore typescript is going to add that optional chaining so now we only run this length if it's actually equal to a string if we have some kind of value so if we won't be able to find a book which is the current case then this actually won't trigger the runtime error now if we're successful then we'll be able to nicely see the length of the book you know what I will change this one around I'm just going to go here to Found book and set it equal to uppercase let me do it this way so we're going for uppercase let's invoke that and then this one I'll just log it again it really depends whether we're able to find the book or no so now let me move this pH book set it up here in my my console and let's see what is going to be the result so I'm going to navigate over here if everything is correct I'm going to get my four if I'm not successful then essentially it's just going to be undefined but I won't have that runtime error where I'm trying to access the property on undefined hopefully that is clear okay and before we move on to the next topic let's work on a small Union type challenge where first we want to create the order status and in there we'll set up the literal types and also we want to set up the discount which can be a number or string type and you know what just because I like to break the rules I'm going to start with the second one doesn't really matter I'm going to go with number or string by default I'll set it equal to 20 or any other number value and I also want to test it whether I can set it equal to 20% now this works but if I'll try to set up discount equal to True essentially a Boolean typescript will yell at me which is exactly what we expected and also let's set up that order status so order status variable by default is going to be equal to processing but we want to set up those literal types so this variable can be only one of these values so we're going to start with processing then we'll set up our pipe and we're going to go with shipped and also we want to add delivered over here so now we can go to the next line set it equal to one of these ones and everything is going to work but if I'll try to set it equal to canceled again typescript will yell at me so let me just set this one up quickly where if we go with order status I just decide that I'm going to pass this value over here not going to be successful since I can see this red squiggly line let me comment this one out we're done with the challenge and up next we're going to discuss arrays in tapescript and as far as the arrays in typescript the general idea is following let's say I have prices array and it's all numbers so we're going to go over here with 100 75 and then 42 if I want to set up the type which is something I want to do again same deal we go with colon then we go with type in this case number and then we set up the square brackets so now I'm essentially telling typescript that this array will only have numbers so if I had a number 34 everything is fine if file tried to stick hello I'm going to get the error because this one is type string and I explicitly told typescript that this is actually going to be an array of numbers and the same is going to work if I will try to invoke push so if I'll try to add the item number is fine string will cause the error so let me comment this one out the same works with string array let's say we have fruit and this is going to be equal to apple and orange we want to set up the type over here in this case it's going to be a string and the same rules apply if we try to add the item that doesn't match type we get the red squiggly line now be careful with the empty square brackets so if we go here and just come up with random values and set it equal to empty square bracket so if we won't provide the type over here typ script just assumes that this will always always be an empty array so if I set it equal to my array and start adding items typescript will immediately complain and notice as we hover it says well type string is not assignable to an Mt right so be careful with this one I know it's temp thing also be careful when you don't explicitly set up the type so if I were to create an empty values array typescript will get the type but check it out now the type is any so just like before we'll run into those issues because now we can change these values any way we want so we can take the string then it turns into a number and same deal so be careful yes typescript will infer the type but most likely you don't want to set it equal to any so this is the case where we want to create the MD but we explicitly want to say yeah this is going to be type number or string or Boolean or whatever now also while we're still on a subject of typescript inferring the type let's take a look at this example let's say I have the names array and I have over here Peter and Susan so if we hover over the names everything is correct typescript sees that we have over here a list of strings and it correctly says the type for this array is string but here's the gotcha since typescript is inferring those values based on what we have over here in the array it doesn't stop me from doing this and now if we hover over it we can see that actually we have this Union type like I said we'll be coming back to this topic and now we have string or number so essentially now I can add numbers as well therefore be careful when you're relying 100% on typescript to set the type it's not going to stop you from adding different values to the particular array and in that case well the type also is going to change now we can explicitly set up the array to be one or the other type so I can go with array for example and I can say that you know what this array is going to have either string or a Boolean again we still set up the square brackets over here and we set it equal to an array where we set up those two values so we can go with Apple then true which is a Boolean and the same deal orange and let's set the false one over here and with this in place we can start working on our next challenge okay and once we're familiar with arrays now let's work on a tiny challenge where we want to set up the temperatures array which will be type number and colors which is going to be type string and then we also want to set up the mixed array so let's start with temperatures essentially our array of numbers now this one probably is going to be the hardest as far as the spelling yep notice over here me fix that one okay good that took a while then I want to set up my type number and we're going to set up 20 then 25 and then 30 and let's try to push I don't know a string of hot so let's actually then go with push and let's try to pass in the string and we won't be successful so we can nicely comment this one out after that we have colors one so this will be actually type of string and in here we're going to go with red green and blue let's save it and let's try to add a Boolean why not so colors here dot then push and we're looking for a bull and mow which is not allowed and then let's set up the mixed one so we're going to go with variable in this case I'm going to call this mixed array and this one will be either a number or a string so number pipe and we set up a string so let's set it equal to our array and in here you know what just to make it interesting why don't we try to add true so bullan and notice right away I'll have my error so let's go with one then two and then we want to add three and with this in place we can move on to the next topic and up next let's discuss object in typescript in order to do that I'm going to create a car and here I'm going to set up the brand that one will be equal to a let's say Toyota and also I'll set up the year so first let me set up the string over here and then let's go with year and we'll set that one equal to a number and if we want to set up the type annotation it might look a little funky but we want to do it this way we again we go with colon then we go with curly braces and then one by one we set up those properties over here so I have a brand and what is the type well it's going to be string but also I have a year and what is that one well that's a number so again either if I try to add some property manually here where I'm setting up the object or for example if I do it dynamically by going card Dot and then the property value unless this property is in the type annotation it's not going to work I think I'm just going to use the color example so let's say I'll set up the color and it's going to be equal to Blue notice right away I have the complaint because the property is not in my type annotation and the same goes if I go with car and brand yeah I can set it equal to Ford since that's the correct type but again if I go with car and color it's not going to fly so typescript will immediately complain now if you're looking at it and you're thinking to yourself well boy this is super clunky over here I have this object and then actually this is going to be my type annotation don't worry this is just essentially the most basic setup but I wanted to cover it since I wanted you to understand how everything works under the hood but eventually we will cover something called type aliases where we will nicely be able to set up this shape somewhere separately and effectively just reuse the variable so again you won't have this clunky code most likely you won't use it but I definitely wanted you to kind of see this type of syntax so now once I have my first car well I can create another one in this case it's going to be a car one since I'm already using the car variable and then I'm going to go with a different brand and also I'll change the year and I don't think it's necessary for me to repeat all of the steps hopefully it's clear whatever we set up in this type annotation needs to match what we have in the object otherwise typescript is not going to allow us to compile essentially our code and now let's tie two things together I want to tie the arrays with the object and in the process we'll also cover how we have read only option with the typescript as well as the optional properties so first I want to create three objects I want to create book pen and notebook and I want to add them to the items array which by default is going to be let's say empty but we'll set up the types in a second so first let's just go with items not going to place anything inside of it and then let's create those three variables so in here we're looking for a book it's going to have two things we're going to go with title we'll set it equal to book and we'll also have cost okay set it equal to 20 and then I'll change this one around to pen okay and the cost I mean again totally relevant I'm going to set it equal to 10 I guess and then I want to go with notebook but for Notebook actually want to remove the cost and like I said now I want to store all of these three values over here in the items but here's the kicker though I do want to make sure that all of them have the same shape now as we're looking at it we can clearly see that it's not the case with the notebook but let's imagine that we don't know that and at this point we have two options we can either repeat the same steps like we did for the car so effectively I can just set up this type annotation for all three of them one by one or since I have an array and I can also set up the type for array I can do it in one place where I have the items so far we know that we can set up the array to be equal to a string or a number or a bullion correct and we also cover the type Union but we can also do something like this where I can say yeah this is going to be an array of objects and then each object needs to have this particular shape now what is going to be the shape I'll say title is equal to a string or I'm sorry I don't know why I'm placing this in the quotation marks and then also I want to set up a cost so we're going to go with cost and we'll set it equal to a number and now one by one as I'm adding these items to my array once I get to a notebook check it out now typescript is like Hey listen this notebook that you're adding well notice it only has the string it doesn't have the cost so whatever type you set up over here well it doesn't match so again super useful where instead of setting them one by one if we have an array we can set it in one place because we also can set up types for array now what is the solution well technically we can go back and add cost over here but we also have this option of adding optional properties now please keep in mind you can use the same optional property over here as well when you're setting up the type annotation for an object I'm just doing it here in Array since this is where we're currently working hopefully that is clear and now I don't have the error because when I set up the cost to be optional well it could be there or it potentially could be missing which is the case for a node and what's also really interesting is that with typescript we can set up the properties to be read only again same deal of course we can set it up over here but in my case I'm going to do that for the title where right before I set up my property I'm going to go with read only so now if I go with items and I access let's say the first one here and if I try to overwrite the value so dot title is equal to a new book for example it's not going to fly so now typescript is immediately complaining that Hey listen title is readon so you cannot change this value over here so let me comment this one out this concludes the object fundamentals in typescript and now we can start working on the next challenge so now let's work on the objects challenge where we want to set up the bike we want to set up the laptop then we'll create some products and we're going to store it in the array so let's start with our bike that will be my object let me come up with some kind of values over here then we also want to add the year and now let's set up our type annotation so we're going to go with colon then brand will be equal to string and also we'll have the here and we'll set it equal to a number that should do it now we just want to change it to a laptop so let me copy this one change the name then brand stays year stays we're just going to add a different string value this case it's going to be Dell and also change the year and now let's see some errors so if I'm going to go with bike and year and set it equal to Old it's not going to fly why well because year is set to be equal to type number and same is going to work if I'm going to create a second laptop so I'm going to go with laptop 2 and it's only going to have a brand so we're not going to have the year so if I'm going to set it like this notice we g

Original Description

Master TypeScript from basics to advanced concepts through hands-on tutorials covering type annotations, generics, data fetching, Zod library, and more, with practical challenges for effective real-world application. Code: https://github.com/john-smilga/typescript-course Course developed by @CodingAddict ❤️ Try interactive TypeScript courses we love, right in your browser: https://scrimba.com/freeCodeCamp-TypeScript (Made possible by a grant from our friends at Scrimba) ⭐️ Contents ⭐️ ⌨️ (0:00:00) Intro, Type Annotations, Arrays ⌨️ (0:55:40) Objects and Functions ⌨️ (1:54:57) Alias and Interface ⌨️ (3:02:53) Tuples and Enums ⌨️ (3:59:10) Type Guards ⌨️ (4:31:02) Generics ⌨️ (5:10:25) Fetch Data ⌨️ (5:43:05) Classes ⌨️ (6:05:17) Tasks ⌨️ (6:47:18) React with TypeScript 🎉 Thanks to our Champion and Sponsor supporters: 👾 davthecoder 👾 jedi-or-sith 👾 南宮千影 👾 Agustín Kussrow 👾 Nattira Maneerat 👾 Heather Wcislo 👾 Serhiy Kalinets 👾 Justin Hual 👾 Otis Morgan 👾 Oscar Rahnama -- Learn to code for free and get a developer job: https://www.freecodecamp.org Read hundreds of articles on programming: https://freecodecamp.org/news
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from freeCodeCamp.org · freeCodeCamp.org · 0 of 60

← Previous Next →
1 React: Production Server Setup Part 2 - Live Coding with Jesse
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
2 cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
3 Browser history tutorial - Beau teaches JavaScript
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
4 Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
5 React: Parameterized Routing with Next.js - Live Coding with Jesse
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
6 React: Dealing with jQuery Issues - Live Coding with Jesse
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
7 setInterval and setTimeout: timing events - Beau teaches JavaScript
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
8 Browser and Device Testing - Live Coding with Jesse
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
9 Last Minute Updates - Live Coding with Jesse
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
10 Post Launch Updates - Live Coding with Jesse
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
11 React: Setting Up Google Analytics - Live Coding with Jesse
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
12 React: Masonry Layout - Live Coding with Jesse
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
13 Load Balancing Digital Ocean Droplets - Live Coding with Jesse
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
14 try, catch, finally, throw - error handling in JavaScript
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
15 Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
16 Graphs: breadth-first search - Beau teaches JavaScript
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
17 React: Masonry Layout Part 2 - Live Coding with Jesse
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
18 React: WordPress API Live Search - Live Coding with Jesse
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
19 Creating WordPress Custom Post Types - Live Coding With Jesse
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
20 Dates - Beau teaches JavaScript
Dates - Beau teaches JavaScript
freeCodeCamp.org
21 Miscellaneous Front End Updates - Live Coding with Jesse
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
22 Merging a Pull Request from GitHub - Live Coding with Jesse
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
23 React + Prettier + Standard JS - Live Coding with Jesse
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
24 React: Sortable Responsive Table - Live Coding with Jesse
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
25 Geolocation Sorting by Distance - Live Coding with Jesse
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
26 Tradeoff Matrix - Agile Software Development
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
27 The Definition of Ready - Agile Software Development
The Definition of Ready - Agile Software Development
freeCodeCamp.org
28 Getting first React job without experience - Ask Preethi
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
29 React: Google Analytics Click Tracking - Live Coding with Jesse
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
30 Submitting a PR to an Open Source Project - Live Coding with Jesse
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
31 Should I go back to school to get CS degree? - Ask Preethi
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
32 Hero Section CSS Changes - Live Coding with Jesse
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
33 Working Agreement - Agile Software Development
Working Agreement - Agile Software Development
freeCodeCamp.org
34 A day at Pennybox with Co-Founder Reji Eapen
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
35 React: Sorting and Filtering Data - Live Coding with Jesse
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
36 React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
37 React: Building a New UI - Live Coding with Jesse
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
38 Definition of Done - Agile Software Development
Definition of Done - Agile Software Development
freeCodeCamp.org
39 Getting started with jQuery (tutorial) - Beau teaches JavaScript
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
40 Making a React Blog with WordPress Content - Live Coding with Jesse
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
41 React, NextJS, CSS - Live Coding with Jesse
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
42 jQuery events - Beau teaches JavaScript
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
43 React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
44 React: Working with API Data - Live Coding with Jesse
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
45 React: Refactoring Components - Live Streaming with Jesse
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
46 jQuery effects - Beau teaches JavaScript
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
47 More React Refactoring - Live Coding with Jesse
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
48 animate in jQuery - Beau teaches JavaScript
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
49 "Finishing" My React Site - Live Coding with Jesse
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
50 Starting a New React Project (P2D1) - Live Coding with Jesse
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
51 React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
52 The Agile Manifesto - Agile Software Development
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
53 jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
54 React Project 2 Day 3 - Live Coding with Jesse
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
55 The INVEST approach to product backlog items
The INVEST approach to product backlog items
freeCodeCamp.org
56 React Project 2 Day 4 - Live Coding with Jesse
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
57 Chickens and Pigs - Agile Software Development
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
58 React Project 2 Day 5 - Live Coding with Jesse
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
59 jQuery: add and remove DOM elements - Beau teaches JavaScript
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
60 React Project 2 Day 6 - Live Coding with Jesse
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org

This course teaches beginners the fundamentals of TypeScript, from basic concepts like type annotations and arrays to advanced topics like generics and React integration, with hands-on tutorials and practical challenges.

Key Takeaways
  1. Install TypeScript and set up a development environment
  2. Learn type annotations and basic types
  3. Understand and use generics
  4. Fetch data using TypeScript
  5. Implement Type Guards and Tuples
  6. Use Enums and Classes
  7. Integrate React with TypeScript
💡 Mastering TypeScript can improve code quality, maintainability, and scalability, and is a valuable skill for web developers.

Related Reads

Up next
How to Speed Up Your WordPress Website with WP Rocket ⚡Tutorial 2026
Matt Tutorials
Watch →