TypeScript Tutorial for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to the ultimate typescript course in this course i'm going to teach you everything you need to know about typescript from the basics to more advanced concepts so by the end of this course you'll be able to use typescript to build large-scale applications if you're looking for a comprehensive easy to follow well organized and practical course that takes you from zero to hero this is the right typescript course for you everything you need to know about typescript is in one place so you don't need to jump back and forth between random tutorials i'm mush hamidani and i've taught millions of people how to advance their software engineering skills through my youtube channel and online school codewoodmosh.com if you're new here be sure to subscribe as we upload new videos all the time now let's jump in and get started [Music] to take this course you need to know typescript now that was a joke you don't need any familiarity with typescript as i'm going to cover everything from scratch but because typescript is built on top of javascript you need basic familiarity with javascript concepts such as variables and constants arrays objects functions arrow functions destructuring and so on if you need to refresh the basics i have a bunch of tutorials and comprehensive courses you can take i've put the links down below in case you are interested [Music] so assuming that you're the right student for this course now let's talk about how you should take this course first and foremost i want you to watch this entire course all the way from the beginning to the end because every lesson teaches you something new if you have taken any of my other courses before you know that i don't waste your time with repetitive or useless stuff so make sure to watch every lesson now while watching each lesson i want you to take notes you can just write down some keywords on a piece of paper if you don't want to write a lot of notes i strongly believe that the act of writing things down will help you remember new things that you learn now when you get to the end of each section make sure to do all the exercises i've carefully designed these exercises to help you better understand and remember the materials remember the more you practice the better you'll be at typescript or coding in general welcome to the first section of the ultimate typescript course we're going to start this section with a quick introduction about typescript we're going to talk about what it is why we use it and when then we're going to set up our development environment and create our first typescript program next we'll talk about configuring the typescript compiler and we'll finish this section by talking about debugging typescript applications so let's jump in and get started [Music] let's start by talking about the top three questions people ask about typescript what is typescript why do we need it and how is it different from plain or vanilla javascript well typescript is a programming language created at microsoft to address some of the shortcomings of javascript you can think of it like the brother or sister of javascript javascript is like a kid without any discipline who does whatever he or she wants typescript on the other hand is like a kid with some discipline now technically speaking typescript is a programming language built on top of javascript so every javascript file is a valid typescript file but typescript adds some really cool features to javascript that help us build more robust and maintainable applications in less time the most important feature typescript offers is static typing what does that mean well we have two types of programming languages statically typed and dynamically typed languages in statically typed languages like c plus plus c sharp and java we know the type of variables at compile time or while coding for example we can declare a variable of type integer and this variable can only hold integer values nothing else so we cannot set it to a string or another type of object in dynamically typed languages like javascript python and ruby the type of variables is dynamic so it's determined at runtime and it can also change so we can declare a variable set it to a number and then later on change it to a string so this variable does not have a fixed or a static type the type is determined and may change at runtime now this is great and gives us a lot of flexibility but it can also lead to problems what if we pass this variable to a function that expects a number then our application might misbehave or crash now the problem is that we will not know about these issues until we run our application or our unit tests well assuming that we have them in place so we have to test every function with various edge cases to cache these bugs and this is the problem that typescript tries to solve typescript is essentially javascript with type checking with typescript we explicitly set the type of our variables upon declaration just like how we code in statically typed languages then we pass our code to the typescript compiler and the compiler will tell us if we are doing something wrong so we can catch a lot of our mistakes at compile time so if we declare a variable as a number we cannot set it to a string the typescript compiler is going to stop us right there and this happens at compile time so we don't have to run our application or our unit tests and test every piece of code to cache these errors we can catch a lot of them simply by compiling our application okay but typescript is more than just type checking most code editors these days have great support for typescript so they can detect the type of our variables and offer productivity boosting features like code completion and refactoring also typescript includes additional features that help us write cleaner and more concise code now over time these features get added to javascript but because we have various browsers and runtime environments for executing javascript code it takes some time until these features are implemented in various browsers so by coding in typescript we can use the features of future javascript so in a nutshell typescript is built on top of javascript and we can use it wherever we use javascript on the front end or the back end so anything we can do with javascript we can also do with typescript now all these great benefits aside let's talk about the drawbacks of typescript first with typescript there is always a compilation step involved because at this time browsers don't understand typescript code so we have to give our code to the typescript compiler to compile and translate into javascript this process is called transpilation second with typescript we have to be a bit more disciplined when writing code so if you're a lazy programmer like our famous old john smith and want to get things done quickly you may feel typescript is getting in the way and that's true but if you're working on a large project with multiple developers you would end up wasting more time coding in vanilla javascript and catching those nasty bugs so then you really want to use typescript for simple applications you can totally get back to old vanilla javascript if that's what you prefer alright that's all about typescript next we're going to set up our development environment [Music] all right the first thing we need is node because we're going to use node package manager or npm to install the typescript compiler i believe as a student of this course you should have node on your machine but if not head over to nodejs.org and download the latest version over here once you do that then open a terminal window and run npm that is short for note package manager which we're going to use for installing third-party packages in this case typescript then we type i that is short for install dash g for installing this globally so we can access the typescript compiler in every folder and then we type the name of the package typescript now if you're on mac or linux and you get a permission error while running this command you have to prefix it with sudo or sudo well more accurately this is sudo because it's short for super user do but that aside let's go ahead and install the typescript compiler okay great now to verify our installation we type tsc that is shortboard typescript compiler dash v to get the version so here i'm running typescript version 4.6.3 you might install a newer version but don't worry because everything i'm going to teach you here will apply to newer typescript compilers now in this course just like my other courses i'm going to use visual studio code or vs code as my code editor you're welcome to use any editor you prefer but if you want to follow along and use some of the shortcuts i'm going to teach you i highly encourage you to use vs code in case you don't have it you can get it from code.visualstudio.com alright so go ahead and set up your development environment because in the next lesson we're going to write our first typescript program [Music] all right now i'm going to go to my desktop folder and create a new folder for our project called hello dash world you can call it anything you want and you can put it anywhere on your machine now let's go into this folder and open it with vs code so we type code period now if this doesn't work on your machine you can simply drag and drop this folder onto vs code okay so here's our project now let's add a new file here called index.ts so every typescript file should have the ts extension now earlier i told you that typescript is built on top of javascript so we say typescript is a supersort of javascript which means it has everything in javascript plus some additional features so here we can write any javascript code and that is valid typescript code so we can write console.log and print hello world now we can go back to our terminal window here or we can use the embedded terminal window in vs code so back in vs code under the view menu look we have terminal the shortcut on mac is control and backtick so we can open the terminal window right here and using typescript compiler we can compile index.ts okay now let's open our project folder look we have index.js which is the result of compilation so we have the exact same code here because in index.ts we haven't used any typescript features so let's write a bit of typescript code so here in index.ts i'm going to declare a variable using the let keyword i'm going to call it h and annotate it with number so by typing a colon followed by the type of variable we can annotate or explain a variable now we can initialize it to let's say 20. now here's the beautiful part because we have declared age as a number we cannot set it to a string or another type of object look we get this error right here it's saying type string is not assignable to type number this is the beauty of using typescript with typescript we can catch a lot of our mistakes at compile time we don't have to run our application or our unit tests to find that we accidentally set a number to a string so let's remove this bad line and recompile our file so back to the terminal tsc index.js good now take a look over here look at the javascript code that the typescript compiler generated so instead of the let keyword here we have var because by default the typescript compiler uses an older version of javascript called es5 which is short for ecmascript 5. so ecmoscript is a standard or a specification while javascript is an implementation of that specification so es5 is an old specification it's been around for a long time and all these features have been implemented in our browsers for a very very long time i think more than a decade now in the next lesson i'm going to show you how to configure the typescript compiler to target a newer javascript version so the code that will be generated would be more modern so here's the interesting part instead of let we're using var and we don't have our type annotation this is purely for the typescript compiler the actual javascript code doesn't specify the type of this variable okay so that's it for now starting from the next section we're going to explore typescript features in detail next i'm going to show you how to configure the typescript compiler [Music] all right let's talk about creating a configuration file for the typescript compiler so here in the terminal we run tsc double hyphen in it so this created a configuration file called tsconfig.json with these settings so let's close the terminal window and open ts config right here so in this file we have a number of settings and as you can see most of these are commented out by default we're only going to use a handful of them so don't be intimidated by all these settings you don't have to learn all of them in fact nobody knows all of them i don't know all of them either now in case you're curious in front of each setting you can see a description of what that setting is for so let's talk about a few of them in this lesson the first one is target which specifies the version of javascript that the typescript compiler is going to generate so this is set to es 2016 which is an old standard and it's been implemented in all browsers out there now depending on where you want to deploy your application you can use a higher target and that often results in shorter and less concise code so if we remove this value and press ctrl and space we can see all valid values so we have yes 2015 16 17 18 and so on now in this lesson i'm going to leave this at yes 2016 because this is the safest option for all browser applications out there but again depending on where you want to deploy your application and how much of older browsers you want to support you can use a higher target now the next setting we have here is module which is set to common js we'll talk about this setting later in the course where we talk about modules now in this section in the module section we have a setting called there which specifies the directory that contains our source files so let's remove the comment by pressing command and slash on mac or ctrl n slash on windows so this is set to period slash which represents the current folder now by convention we often put our source code into a separate folder so back to our project panel let's create a new folder here called src and then move index.ts right here okay now i'm going to delete index.js we don't need it for now okay so now we're going to change router to period slash source now we have a similar setting here under the emit section that setting is called outer and this specifies the directory that will contain our javascript files so let's enable this and change it to dist so when we compile our code using the typescript compiler our javascript files are going to be stored in this or distributable folder okay now here we have another useful setting called remove comments so if we enable this the typescript compiler is going to remove all the comments that we add in our typescript code so the generated javascript code is going to be shorter okay now another useful setting in this section is no emit on error so by default when we compile our code even if you have errors in our code the typescript compiler will still generate javascript files this is probably not what we want so the best option is to always enable this setting so if you have any mistakes in our code the typescript compiler is not going to generate any javascript files okay now with this configuration file in place now we can go back to the terminal and compile our code simply by running tsc without any arguments so we don't have to type index.ts we just run tse and this will compile all typescript files in this project take a look all right now we have a new folder called disk that contains our javascript file so this was the basics of ts config as we go through the course we'll explore more of this useful settings [Music] all right now let's see how we can debug our typescript applications in vs code this is very useful when things go wrong and our code doesn't work as expected so we can run our code line by line and see what exactly happens under the hood there are a few steps we need to follow first we go to tsconfig.json and here in the emit section we enable the source map feature so a source map is a file that specifies how each line of our typescript code maps to the generated javascript code let me show you so back to the terminal let's recompile our code good now look into this folder we have a new file called index.js.map this is our source map so if you look over here you see some code that specifies how our typescript code maps to our javascript code now this is not for us to understand this is for debuggers it's for machines okay so let's close this file now to make debugging more interesting let's go to index.ts and write some logic we can say if age is less than 50 we're going to add 10 to it okay now we're going to click on the first line to insert a breakpoint so when we start debugging the execution stops right at this line at this breakpoint from this point forward we can execute our code line by line okay now we go to the debug panel and click on create and launch the json file now from this drop down we select node.js and this creates a new file called launch.json in our project i'll show you that in a second so this is a json file with some configuration that tells vs code how to debug this application so we're going to use node to launch this program and here we have a label called launch program which you will see in a second and we can see our program starts here so in the source folder we have index.ts and our output files are stored in our workspace on our project in files with the js extension now here we need to add one more setting it's called pre-launch task we're going to set this to a string with this value tsc colon space build space hyphen space tsconfig.json make sure to type this out exactly as i have shown you here all these spaces matter okay so with this setting we are telling vs code to use the typescript compiler to build our application using this configuration file okay now we go back to index.es and to start debugging we can go to the debug panel and click on launch program this is the label that i just showed you now look at the shortcut it's f5 i always prefer to use shortcuts so let's start debugging good now our program started and the execution stopped right on this line at this breakpoint now on the top we have a bunch of tools for executing our code we have step over for executing one line we have step into we're stepping into a function currently we don't have any functions so it's not useful we also have step out this is useful for stepping out to the function we have restart and stop so in the tooltip that you see in front of each tool you can see the shortcut so the shortcut for stepping over a line is f10 let's press that so this line was executed now on the left side under variables you can see all the variables that are detected in this debugging session so under local we have age that is set to 20. as we execute each line you'll see the value of this variable getting updated now if there's something that you don't see in the variables window you can go to the watch window and insert a watch so we're going to watch the age variable current is 20. so let's step over this line now we're on this line so let's step over this as well now hcode updated but because our program terminated we don't see its value anymore but if you add one extra line here let's say console.log h let's start the debugging session one more time by pressing f5 now step over f10 f10 f10 and now h is 30. so this is debugging in via score it's very useful when things go wrong we can start our program and execute it line by line all right now that we're done with debugging we can stop the debugging session right here so that brings us to the end of this section starting from the next section we're going to explore typescript in detail hey guys mosh here i just wanted to let you know that this tutorial you have been watching is actually the first hour of my complete typescript course the complete course is about 5 hours long and goes way beyond this tutorial it also comes with exercises and solutions summary notes and cheat sheets a 30-day money-back guarantee and a certificate of completion you can add to your resume so if you're serious about learning typescript and are looking for a job as a front-end or a back-end developer i highly encourage you to enroll in the course in case you're interested i'll put the link in the description box and if not that's totally fine let's move on to the next lesson welcome back to another section of the ultimate typescript course in this section we're going to explore the fundamentals of typescript so you will learn about the built-in types like the any type arrays tuples enums functions and objects the concepts you'll learn in this section will be the foundation for future sections so don't skip any lessons now let's jump in and get started [Music] so javascript has built-in types like number string boolean null undefined an object now typescript extends this list and introduces new types like any unknown never enum and tuple as we go through this section you will learn about all these steps in detail but before we get started let's see how we can play with primitive types in typescript so back in index.ts i'm going to delete all this code and declare a variable called sales of type number and set it to a value like one two three four five six seven eight nine so once again we're annotating or explaining the type of the sales variable using this syntax okay now in typescript if you have a large number we can separate its digits using an underscore that makes our code more readable okay now let's also declare a variable called course of type string and set it to typescript and one boolean called is published now let me show you something really cool in typescript we don't always have to annotate our variables because the typescript compiler can infer or detect the type of our variables based on their value for example because we have initialized this variable to a number the typescript compiler knows that this variable is a number so we don't have to annotate it so if we remove the annotation and hover our mouse over this variable look we can see that sales is a number similarly because we have initialized course to a string we can remove the annotation and once again we can see that course is a string and one more time now what if we declare a variable like level and don't initialize it typescript assumes that this variable is of type any we'll talk about that in the next lesson [Music] in timescript we have a new type called any which can represent any kind of values so if we declare a variable and don't initialize it the typescript compiler assumes this variable is of type any so we can set it to a number and then later on we can set it to a string but this is against the whole idea of using typescript because we use typescript for type safety so we get type checking so if we use the any type we essentially lose that feature and the major benefit of using typescript so as a best practice you should avoid using the any type as much as possible let's look at another example let's say we have a function called render that takes a document and simply renders it on the console now look we have a compilation error and the error is saying parameter document implicitly has on any type implicitly means we haven't explicitly or clearly set the type of this parameter so the compiler is inferring or guessing the type of this parameter and that's why we have this error now let's say this is part of a javascript project we're trying to convert to typescript and at this point it's impossible for us to explicitly annotate this with a particular type so we have to use the any type here now here we have two options to turn off this error one option is to annotate this with any so we're telling the compiler hey i know what i'm doing the document is of any type but what if we have tons of errors of this kind we don't want to go to every function and explicitly annotate various parameters with any well there is a nuclear option for that but i don't personally recommend that but let me show you how that works so let's remove the annotation now if you're on mac press command and p if you're on windows press ctrl and p to bring up the search box and go to tsconfig.json now look in the type checking section strict is turned on and this is equivalent to turning on some of the basic type checking features you will learn about these settings as we go through the course now the first setting you see here is no implicit any so let's remove the comment so if this feature is turned on the compiler will complain about implicit any types now let's turn this off and see what happens so back in index.ts the error is gone so use this with caution only if you know what you're doing otherwise there's really no point using typescript because you will lose the major benefits of typescript okay so back to ts config i'm going to revert this code good so that's all about the any type next we're going to talk about arrays [Music] all right let's talk about arrays in javascript we can declare an array like this now the thing about javascript arrays is that each element can be of different type so here we can have two numbers followed by a string and this is totally valid javascript code because javascript arrays are dynamic so each element can be of different type but what if we pass this array to a function that expects a list of numbers then the third element is going to cause some issue right this is where we use typescript so we can explicitly apply a type annotation here and say numbers is a number array now we see the error immediately at compile time so let's fix it good now in this particular case we don't even have to apply the type annotation because every element in this list is a number so if you remove the type annotation the compiler can still infer or guess the type of this variable great but what if we had an empty array here look now the type of this variable is any array which is something we should avoid with any arrays again we can have a mix of different types so the first element can be a number the second element can be of a different type like a string or a boolean so if you want to use an empty array you have to explicitly apply a type annotation here let's say number array now the third line is invalid so let's delete it now let me show you another cool benefit of using typescript and that is code completion or intellisense so if we type numbers that for each and pass an arrow function here like n goes to and then type n period over here we can see all the properties and methods of number objects because our editor knows the type of n it offers code completion so we can see all the methods of number objects this is very useful it's a great productivity boosting feature we don't get this with plain javascript right so that's another benefit of using typescript that's all about the arrays next we're going to talk about tuples [Music] typescript has a new type called topple which is a fixed length array where each element has a particular type we often use them when working with a pair of values for example let's say for each user we want to represent two values an id and an a so we declare a variable and annotate it using a special syntax like this first we add square brackets and then tell the compiler that the first element is going to be a number whereas the second element is going to be a string and then we initialize our variable like this so we have a fixed length array with exactly two elements nothing more nothing less so if we add a third element here we get a compilation error saying type number string number is not assignable to type number string okay so exactly two elements and these elements should have these types the first one has to be a number so if we pass a string again we get a compilation error now just like before here we get intellisense or code completion so if we access the first element we see all the methods of number objects and if you access the second element we see all the properties and methods of string objects again one of the reasons i love typescript now one thing you need to know about tuples is that internally they're represented using plain javascript arrays so if we compile our code we're just going to see a regular javascript array let me show you so in the terminal let's run tsc good now back in our project here in this folder let's open index.js look we just have a regular javascript array so that means back in our typescript code if we type user period over here we can see all the methods of array objects now one of this method is a little bit troublesome and that is the push method so we can call this method and store a third value in this array and the compiler is not going to complain here i believe this is one of the gaps in typescript at the time of recording this hopefully this will be solved in the future so a tuple is a fixed length array where each element has a particular type now as a best practice i would say restrict your tuples to only two values because anything more than that is going to make your code a bit hard to understand for example if you add a boolean and another number here what do these values really represent it's really hard to tell so tuples are useful when we have only two values like key value pairs next we're going to talk about enums [Music] typescript has another built-in type called enum which represents a list of related constants if you know c sharp or java you have seen enums before we have the exact same concept here in typescript so let's say we want to represent the size of t-shirts as constants one way is to define three constants like this small medium and large that's one way and then throughout our code we can reference this constant another way is to group this constant inside an enum so we use the enum keyword then give our enum a name now note that here i'm using pascal naming convention so the first letter of every word should be uppercase okay then we add curly braces and inside the braces we add our members small medium and large once again i'm using the pascal naming convention for the members now when we define an enum we don't need to define these three constants anymore and by default the typescript compiler assigned the first member the value of 0 and other members values like 1 2 and so on now if you don't want to use these values we can explicitly set values so we can set small to 1 and then medium becomes 2 and large becomes three we can also use string values like s if we do this then we have to explicitly set a value for each member so medium and large like this now i'm going to revert this code and just rely on numbers so i'm going to initialize small to 1 and rely on the compiler to set the value for other members so now that we have this new type we can declare a variable like my size of type size and set it to size dot medium okay so this is how we can use enops now let's see what happens if we log my size on the console so back to the terminal let's run the typescript compiler good and then use node to execute our javascript code so we go to the disk folder and pick index.js so look we see the numeric value associated with our enum member okay now let's look at the generated javascript code in this file so back to the project here's our index file take a look so the generated javascript code is pretty verbose it's pretty lengthy now you don't need to worry about understanding this but let me show you a trick back to our typescript file if we define this enum as constant the compiler will generate a more optimized code so let's recompile our code and then look at index.js one more time now we don't see all that code anymore we only have one line for setting my size to 2. again you don't have to worry about the generated javascript code all i want you to take away here is that using an enum we can represent a list of related constants and if we define our in-apps using the constant keyword the compiler will generate more optimized code next we're going to talk about functions [Music] let's talk about how typescript helps us prevent common problems when working with functions so let's define a function called calculate tags and give it an income parameter of type number now let's hover our mouse over the function name look at the type of the return value it's void meaning this function does not return a value if you return a value here like a number now the type of the return value is number so the typescript compiler has inferred the type of the return value for us and that's great but as a best practice we should always properly annotate our functions so all the parameters as well as the return type should be properly annotated especially if you're building an api for other people to use so in this case to annotate the return type we go after the list of parameters add a colon and specify the return type like number or void if we are not going to return a value so let's add number now this has an extra benefit if you forget to return a value or if you return a different kind of value like your string we get a compilation error immediately so as best practice always properly annotate your functions now let's temporarily return zero okay look at the income parameter this is an unused parameter now we have a compiler option for detecting these unused parameters so let's go back to our ts config file in the type checking section we have a compiler option called no unused parameters we have to explicitly turn this on because this setting is not part of strict setting now back to index.ts look we have a warning saying income is declared but its value is never read so let's change this code and say if income is less than 50 000 then we're going to return income times 1.2 now here we have another compilation error saying function lags ending return statement and return type does not include undefined it sounds a bit cryptic but what this error is saying is that if this condition is true we're going to return a number otherwise as you know javascript by default always returns undefined from our functions and undefined is not a number now let me temporarily remove the annotation for the return type look we have no compilation error but this function has a problem if the income is greater than 50 000 we're gonna get undefined from this function and this may cause a bug in our application the good news is that we have another compiler option for detecting these kind of issues where we forget to return a value so back to our ts config file again in the type checking section we have a setting called no implicit returns again we have to explicitly turn this on because this is not part of the strict setting okay now to factor code we have a warning saying not all code paths return a value so now we can fix this problem and say otherwise if income is greater than 50 000 we're going to return income times 1.3 but again it's best to always annotate our functions properly to prevent all these issues so we should always return a number from this function now we have another useful compiler setting for detecting unused variables so if we declare a variable like x and don't use it in this function this is unused now using the typescript compiler we can find these issues in our code so back to ts config here is the setting no unused locals with this feature enabled now back to our code we have a yellow warning saying x is declared but its value is never read so now we can delete this and make our code cleaner so this is the basics of functions now let's add a second parameter here called tax here of type number now we have a warning here saying texture is declared but its value is never read so let's change our condition to if tax year is less than 2022 then return income times 1.2 so now with these two parameters if you want to call this function we have to supply exactly two arguments nothing more nothing less so i'm going to pass 10 000 for the income and 2022 for the tax year if you add an extra argument here we get a compilation error saying expected two arguments but got three if you have been coding in javascript for a while you know that this is valid javascript code so javascript doesn't really care how many arguments we pass to a function we can pass more or fewer arguments than the number of parameters but typescript is very strict about this so here we should pass exactly two arguments so let's remove that but what if you want to make this optional let's say in some places we want to call this function without supplying the tax year well we can make this parameter optional by adding a question mark right here now we have a compilation error on this line saying object is possibly undefined so if we don't supply the tax year by default undefined will be used and we cannot compare undefined with 2022. so here we have two options one option is to use the old javascript trick so we wrap this in parenthesis and then using the or operator we give it a default value like 2022 so if we don't supply the tax year this value will be used otherwise the argument that we pass will be used here okay now i don't like this approach there is a better way we can give this a default value so instead of making it optional we give it a default value like this now we can call this function with or without a tax year if we don't supply an argument for the tax year this value will be used otherwise what we pass here will overwrite the default value okay now with this default value we no longer need to use this ugly expression we can simply compare tax year with 2022 so let's quickly recap what you learned in this lesson as a best practice always properly annotate your functions all the parameters and return types and enable these three compiler options no unused locals no unused parameters and no implicit returns [Music] all right the last thing we're going to cover in this section is objects so let's declare an employee object with an id property now you know that in javascript objects are dynamic so their shape can change throughout the lifetime of our programs so once we have an employee object then later we can give it a new property like name and this is totally valid in javascript but as you can see this is not valid in typescript the compiler is saying property name does not exist on this type so this type is an object with an id property which is a number so just like all the variables we have declared so far the typescript compiler has inferred the shape of this employee object so if you hover our mouse over employee we can see its shape it's an object with an id that is a number now just like all the variables we have declared so far we can explicitly apply a type annotation here so after employee we add a colon followed by braces and inside the braces we define the properties of an employee object so every employee should have an id that is a number and a name that is a string now the previous error on this line is gone but we have a new kind of error let's find out the compiler is saying property name is missing so the reason we're seeing this is because every employee should have these two properties but while initializing this object we haven't supplied the name property now here we have two options one option is to set the name to an empty string we cannot set it to null or undefined we'll talk about this in the next section so we should either set it to an empty string or we can make this property optional and then we don't have to supply the name property while initializing an employee now even though typescript allows us to do something like this this is something we should avoid because conceptually it doesn't make sense to have an employee without a name every employee should have a name it would make sense to make the fax property optional because not everyone has a fax machine right so always make sure the code you write conceptually makes sense don't blindly use features of typescript or any other programming languages okay so in this case we're not going to use an optional property and that means we should either set the name to an empty string or initialize it right here okay now we have an error because i used a period okay so now we don't need this last line anymore okay now sometimes we want to make certain properties read only so we don't accidentally change them later on so with our current implementation we can change the idea of an employee anytime and this is not valid this is where we use the read-only modifier so we applied before the name of the property and now the typescript compiler prevents us from accidentally modifying the value of this property okay good now how can we define a function or more accurately a method in this object let's say every employee object should have a retirement method so in our type annotation we need to define the signature of this method we need to specify how many parameters it's going to have what is the type of each parameter and what is the type of the return value so we're going to have a retire method with one parameter that is date now here we use the arrow function syntax so first we add parenthesis and inside parenthesis we specify the parameters so we're going to have a date parameter of type date this is just a built-in data object in javascript and typescript so we only have one parameter then we use a fat arrow and here we specify the type of the return value we don't want to return any value so we're going to use weight now we have a compilation error saying property retire is missing because when initializing this object we haven't supplied the retired method so let's do that real quick all right retirement is going to be a method with one parameter and over here i just want to lock the date on the console pretty simple so this is how we can work with objects now i know this syntax this type annotation is a little bit messy it's making our code a bit verbose or noisy so in the next section i'll show you a better way to work with objects welcome back to another section of the ultimate typescript course in this section we're going to explore more advanced types in typescript so you will learn how to use type aliases to reuse types and simplify your code how to use unions and intersections to combine types how to narrow types how to work with nullables as well as the unknown and never types so let's jump in and get started [Music] alright so this is the employee object that we created at the end of the previous section now there are three problems in this implementation the first problem is that if you want to create another employee object we have to repeat this structure we have to repeat this shape so we'll end up duplicating our code which is bad we always want to confirm to the dry principle don't repeat yourself now the second problem is that the other employee object might have other properties so these two employee objects might not have a consistent shape because we don't have a single place to define the shape of an employee object now the third problem is that overall this structure is making our code a little bit hard to read and understand this is where we use a type alias using a type alias we can define a custom type let me show you so on the top we start with the type keyword then give our new type and name and once again here we use the pascal case so employee with a capital e then we set it to braces and inside the braces we define all the properties and methods an employee object should have so i'm going to go in this annotation select these three lines and by pressing alt and up we can move these lines up okay now when defining this employee object we annotate it with our new type employee okay so now we have a single place where we define the shape of an employee object and we can reuse this in multiple places this is the benefit of using a type abs [Music] all right let's talk about union types with union types we can give a variable or a function parameter more than one type so let's define a function for converting weight from kilogram to pounds now we give it a parameter called weight now let's assume that this parameter can be either a number or a string so we annotate it with number or string so using a vertical bar we can create a union type now we can call this function in two ways we can give it a number or a string like 10 kilograms okay now let's finish up this example so we're going to annotate the return type and return a number now in this function at this point we don't know if the weight is a number or a string so if we type weight period we only see the properties and methods that are common between numbers and strings so both numbers and strings have these three methods to locale string to string and value of so here we are not seeing methods that are specific to numbers or strings and this is where we use a technique called narrowing so we're going to narrow down this union type into a more specific type so here we can say if type of weight equals number now in this block the compiler knows that the weight is a number so if we type weight period we see all the methods that are available in number objects and by the way we don't necessarily need the code blocks here in this line if you have a one-liner and type weight period we still see all the methods available in numbers okay so what are we going to do here we're going to return weight times 2.2 otherwise if you end up here that means weight as a string so now we see all the properties and methods of string objects okay so to finish this example here we're going to return first we need to convert the weight to an integer so we call parsend pass the weight and then multiply it by 2.2 okay now back to the terminal let's compile our code and see what we get all right we're going to go to index.js take a look our union type is not part of the generated javascript code it's purely for the compiler to do is type checking [Music] so in the previous lesson you learned that using a union type we can say a variable or a function parameter can be one of many types right now we have another technique for combining types called intersection so instead of a vertical bar use an ampersand and now this type represents an object that is both a number and a string at the same time now technically this is impossible we cannot have an object that is both a number and a string at the same time so let's look at a more realistic example i'm going to use our type alias to define a new custom type called draggable so this represents an object that can be dragged on the screen now what properties or methods do we need in a draggable object well at least we need a method called drag which takes no arguments and returns void now similarly we're going to define another type called resizable and here we need a resize method that should take two parameters like the new width and the new height but for simplicity let's get rid of all that noise and just add no parameters and say this method returns void okay so now we have two separate types and using an intersection type we can combine them into a new type so we can define a new type called ui widget which is draggable and resizable so this is an intersection type now with this type in place we can declare a variable called textbox which is a ui widget now to initialize this object we need to implement all members of draggable and resizable objects so we need to implement the drag and resize methods so drag as a simple method and so is the resize method so this is type intersection in action [Music] sometimes we want to limit the values we can assign to a variable this is where we use literal types so let's declare a variable called quantity and assume that the quantity can either be 50 or 100 but nothing else now here's the problem if we annotate this with number this can take any numbers any valid numbers in javascript right so to limit the values we can use here we use a literal type so instead of annotating this with the type like number will annotate it with a literal meaning an exact or specific value so i'm going to replace number with 50. now quantity can only be set to 50 nothing else so if you set it to 51 you get a compilation error now you might think this is not useful well that's true but what if we apply the union operator here so we can say the quantity can be 50 or 100. now we can set it to 50 or 100 right but we're not done yet we can make this code even better so instead of hard coding these literal values here we can create a custom type using a type alias so we define a new type called quantity which can be 50 or 100 and then we annotate our variable with our new type so what we have over here is called a literal type now literals don't have to be numbers they can also be strings for example we can define a new type called metric which can be centimeter or inch okay so that's all about literal types next we're going to talk about nullable types [Music] all right let's talk about working with null values so by default typescript is very strict about using null and undefined values because as you probably know these values are common source of bugs in their applications so let's look at a real example let's define a function called greet that takes a name which is a string now in this function we just want to do a console.log and print name the to uppercase now in vanilla javascript we can call this function and accidentally give it null or undefined that is totally valid javascript code but when we run our program our program is going to crash because we cannot call this method on a null or an undefined object so this is why null and undefined values are a common source of problems and that's why by default the typescript compiler stops us from using null or undefined values so here we have an error saying argument of type null is not assignable to parameter of type string let me show you where this comes from so let's go to our ts config file in the type checking section we have a compiler option called strict null checks that this is enabled by default as part of the strict option so if strict is set to true strict null checks is also true but we can overwrite it and turn off this feature now back to index.ts the error is gone so this is why by default typescript is very strict about using null values so technically we should never use this option we should never turn it off so i'm going to rewrite this back but what can we do in this function what if we want to have the ability to use a null value perhaps if we don't have a name you want to print just a generic message like hola meaning high in spanish so here we can say if name is truthy meaning it has a value then we're going to print name.to uppercase otherwise if it's null or undefined we're gonna print hola okay but we cannot pass a null value here this is where we use a union type once again so we annotate this parameter with string or no now we can pass a null value but we cannot pass undefined because this is not a valid value for this parameter so if you want to have the ability to pass undefined as well again we're going to use the union operator [Music] now when working with nullable objects we often have to do null checks for example let's define a type alias called customer and give it a birthday property of type date now let's define a function for getting a customer from a database so we give it an id which is a number and we get either a customer or null in case there is no customer with the given id now in this function let's write some basic logic like return if id equals zero then we return null otherwise we return a customer object with this birthday pretty simple now let's declare a variable and here we call getcustomer and pass zero now let's imagine we want to print the customer's birthday so console.log and here we pass customer dot birthday now here we have a compilation error because customer might possibly be no so as you know one way to solve this problem is like this we check if customer is not known then we execute this piece of code now let's take this to the next level and assume that under certain circumstances this function might return undefined so we add undefined here and now we have to expand this if statement and check for undefined so if customer is not null and it's not undefined either then we print the customer's birthday that works but there is a simpler way to write this code in typescript we can remove this if statement and use what we call the optional property access operator so because customer might be null or undefined right after it we add a question mark and then we add the chaining or the dot operator so this question mark followed by the chaining operator is called the optional property access operator so now this piece of code gets executed only if we have a customer that is not null or undefined let's see this in action so we're passing 0 and we get a null object so if we execute this code we get undefined so the result of this expression is undefined but if we pass one we get an actual customer object so we'll see the customer's birthday on the console there you go okay so this is optional property access operator now we can take this to the next level let's make the birthday property optional now let's say we want to print the full year of the birth year so over here we have to call dot get full year now once again we have the same compilation error because the birthday property might possibly be undefined once again to solve this problem we can use the optional property access operator so now this piece of code gets executed only if you have a customer and that customer has a birthday otherwise the result of this expression is undefined okay now we also have what we call optional element access operator and this is useful when we are dealing with arrays so we might have an area of customers and we want to print the first customer on the console now if this array is going to be non or undefined of course we have to check if customers is not null and it's not undefined then we're going to access the first element now this is where we can use the optional element access operator so before accessing this element we use a question mark and a dot okay now we also have the optional call operator which has the exact same syntax so let's imagine we have a variable called log which is going to reference a function so for simplicity i'm going to annotate this with any and this might be set to a function like a function that takes a message and prints that message on the console or we might set this to no right now let's say we want to call this and pass some value if we run this program our program is going to crash because log is not so this is where we can use the optional call operator so this piece of code will get executed only if log is referencing an actual function otherwise we'll get undefined hey guys mosh here i just wanted to let you know that this tutorial you have been watching is actually the first hour of my complete typescript course the complete course is about five hours long and goes way beyond this tutorial it also comes with exercises and solutions summary notes and cheat sheets a 30-day money-back guarantee and a certificate of completion you can add your resume so if you're serious about learning typescript and are looking for a job as a front-end or a back-end developer i highly encourage you to enroll in the course in case you're interested i'll put the link in the description box [Music] you
Info
Channel: Programming with Mosh
Views: 1,220,618
Rating: undefined out of 5
Keywords: typescript tutorial, learn typescript, typescript, typescript tutorial for beginners, mosh hamedani, code with mosh, programming with mosh, web development, javascript, typescript course, typescript crash course, what is typescript, typescript for beginners, typescript basics, ts, introduction to typescript
Id: d56mG7DezGs
Channel Id: undefined
Length: 64min 28sec (3868 seconds)
Published: Mon May 23 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.