TypeScript Course for Beginners 2021 - Learn TypeScript from Scratch!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Should I learn JavaScript or typescript? And are they easy to transfer to just Incase I need to use the other?

👍︎︎ 2 👤︎︎ u/Nemos245 📅︎︎ Jan 22 2020 đź—«︎ replies
Captions
my name is Mexican Schwarz Villa and I will be your instructor in this course now this course is about typescript superset to JavaScript so a programming language which actually builds up on JavaScript you could say it takes JavaScript to the next level with typescript you will see in this course you can write less error-prone much better and cleaner code and also use some exciting new features which don't exist like this in JavaScript now in this course you will learn typescript from scratch you don't need to know anything about types good to get started basic JavaScript knowledge absolutely suffices you will learn all the basics of typescript how it works why we use it the different advantages it offers we'll dive into the core types it provides and will gradually build up knowledge and dive into more and more advanced types good features throughout this course now this course is both a course that focuses on the theory and showing a broad variety of features as well as showing all these features in action and rail projects therefore in this course we'll have a real project we'll also have a module where we dive into typescript with react we'll also have a module where we dive into typescript with node and express so that by the end of this course you really feel comfortable using types could in your next projects and that you know why you would use it and most importantly how you would apply it to any JavaScript project you're working on no matter by the way if that is javascript in the browser with or without any framework or if it's on the server-side so that's all in the course I'm super excited to start this journey together with you and with that I'd say let's not waste any time and let's find out what exactly types code is and which advantages it has to offer so what is typescript what is it all about why would we use it typescript is a JavaScript superset now what does this mean it means that typescript is in the end a language a programming language building up on JavaScript it's not a brand new language instead it takes the JavaScript language and adds new features and advantages to it it makes writing JavaScript code easier and more powerful you could say but we have one huge disadvantage typescript can't be executed by JavaScript environments like the browser browsers can't execute typescript and for example node.js also can't execute typescript so the environments where we can execute JavaScript don't support typescript what's the idea behind typescript then it's a better version of JavaScript and we can't use it well not quite typescript is a programming language but it's also a tool it's a powerful compiler which you run over your code to compile your typescript code to JavaScript so what you get as a result when writing code in typescript is JavaScript but you didn't write that JavaScript code you wrote typescript code with all the new features and all the advantages and you get normal JavaScript code well that of course brings up one important question how can types could add new features if what you get in the end is regular JavaScript and the answer is the typescript compiler compiles these new features to JavaScript workarounds so in the end it might give you a nicer syntax an easier way of doing something and it will then compile that nicer easier way to a more complex JavaScript snippet which you would have to write otherwise so it's not magic of course it can't add what's not possible at all in the JavaScript language but it can add new features that simply are easier to use nicer syntax things like this in dition types of course that's one important thing which the name already implies it adds types it adds a feature to D JavaScript language ed which will have a close look in a second which will actually give you as a developer an opportunity of identifying errors in your code earlier before your script runs and the error occurs at runtime in the browser so it does not only give you some new features and nicer ways of doing something it also gives you extra error checking where errors which you would otherwise get as runtime errors can be caught and fixed early during development so why would we use typescript consider this example a fairly simple JavaScript function which adds two numbers now when I call it please notice that I'm passing in two strings instead of two numbers and I'll show you a real example where something like this could happen realistically in just a second so we're calling this function with two strings and as a result what you would actually get here is probably an unwanted behavior because if you add two strings javascript will concatenate the strings instead of doing a mathematical calculation here so the result would not be five but 23 a concatenated string of the two numbers this is an error you could have in JavaScript it's not a technical error you probably won't get a runtime error but you have a logical mistake in your code and that of course can lead to huge problems in the web applications you're writing with JavaScript now of course in JavaScript we have mitigation strategies we could add an if check in the function to check the types of the inputs at runtime we could also validate and sanitize user input and whilst we might want to do all of that it would also be nice if we could catch errors like this during development already and thankfully this is possible with typescript because developers can write invalid code here in introduced box like this in JavaScript and with typescript we have a tool that helps us write better and avoid such problems so let's have a closer look at this here is this same example basically in a real project you find this simple project the index.html file in this javascript file attached to this video in a zip file you can simply open this and then open the index.html file you can also open the code in any text editor of your choice here I'm using Visual Studio code and it will come back to my exact setup later in this module for now you can just open these two text files with any text editor now what you'll find in there is this JavaScript file which interacts with this index.html file and in that index.html file you'll find two inputs and a button and any JavaScript file which gets imported here we basically reach out to these elements then we have a function here and an event listener on the button that triggers the function and locks the result of the function here in the console now if we simply open that index.html file by double clicking on it in the Windows Explorer or the Mac finder so that it opens up in a browser what you'll see is this the two inputs and the add button and here I opened the browser developer tools as well now if you enter ten and five here for example you might expect to see fifteen as a result here on the right but instead you see 105 and this shows us a weakness of JavaScript here this is not a technical error it's not an error which is thrown but it's a logical error in our application now where is this error coming from though well here in JavaScript I reach out to these two inputs and when the button is clicked in the end I get the values of the two input elements and a pastor here to add and here it's important to know that in JavaScript when you access the value of an input element it's always a string always no matter which type of input disease if this is of type number or not it's always a string so I'm passing in two strings to this function the end and if you add two strings in JavaScript they get concatenated instead of added mathematically which is why we see one hundred and five ten and five concatenated this is the issue with javascript here and this is something where typescript can help us now without typescript we could of course add a if check here and check if the type of num1 is equal to number and if the type of num2 is equal to number and if that is the case then I return my calculation like this else I might throw an error or I at least convert both to numbers by adding a plus in front of each parameter here now this is some code we could write maybe a bit more refined than this in JavaScript and with that we would ensure that we convert numbers or the inputs to numbers if they're not numbers yet so with that if I reload this and I repeat this now we get 15 because of our changed code so of course you can do this in JavaScript and this is vanilla JavaScript nothing typescript is about it but we wrote some extra code for an error which I actually would like to prevent in the first place I don't want that this happens I want to make sure that we can't even pass strings here to add because add should be a function that only operates on numbers so that in there we don't need to check whether we get a number or not so I want to keep this function in this state it was before I want this function here just like this and that is where typescript can help us so typescript can help us in such situations as I just showed now in order to see how it helps us let's install it so on typescript Lang org you can click on download' and there you'll learn how to install it and we will actually install it with this command which uses the NPM tool and the NPM tool is part of the note Rhea's package so even though we're not going to write no trayers code here we still need to install node.js simply because behind the scenes that will also be used by some tools we use and when we install node.js we also install NPM the node package manager a tool which we then can use to install typescript globally on our machine so simply visit note reyes org and there install the latest version you find here simply click on this button it will then download an installer you can walk through that installer it is supported for all operating systems and once you have noches installed you will be able to run this command simply open up your normal terminal or command prompt and then copy in that command important on Mac and Linux you might need to add sudo in front of this to get the right permissions on Windows this will not be required so simply make sure you then install typescript with this command enter your password in case you should be prompted for it and with that you got typescript installed globally on your machine now what does this mean typescript installed well remember that typescript is a programming language but it's only a programming language that works because we also have this compiler this tool which compiles it to JavaScript so in the end what we installed here is the compiler and everything it needs to know to understand typescript code to convert it to JavaScript so with this we have the compiler installed and we can run the TSC command now which invokes this types of compiler to compile a types good file to JavaScript so to see this in this project we worked on let's simply add a new file using TS dot ts for example any name you want but the extension should be dot TS which stands for typescript now let's copy that JavaScript code into that types could file here in visual studio code I immediately get some errors which we now will fix and this is one great advantage of typescript if you're using the right IDE and my strong recommendation really is visuals to your code and I will come back to it later then you already get great support in the IDE when working inside of typescript files here already it basically lets types could analyze my code and identifies some weaknesses which is great because that's exactly what I want so here in this example let me delete the jobs could only J's file and with death some of the errors are gone because it identified that some constants and so on were used in multiple files but it still gives me an error down there and what you see for example is that it's not sure if there really is a value property now that's a mistake I didn't even consider before in JavaScript but it's true I'm selecting an element by ID here now typescript can't know if this will really work maybe I have a typo in here in this case I wouldn't be able to select an element this element simply wouldn't exist on the page so we might have a typo in typescript does not analyze your HTML code to find out if this works so for one this might fail but even if it succeeds and we select an element there it doesn't have to be an input element it could be any other element and most HTML elements don't have a value property you can access and this already is great typescript forces us to be more explicit to be clearer about our intentions and to double check our code and for example here and you don't need to understand all that syntax we will learn it step by step throughout the course but for example here we could let type know that we are sure that we will get an element by adding an exclamation mark this basically tells typescript this will never yield null this will always find an element and as a developer I of course know that this will always find an element because I double check that ID and I see yeah I have that ID here now in addition I also know it will always be an input element so we can use as HTML input element a syntax called typecasting which I will also explain in greater detail later to let typescript know which type of element this will be we can apply this to the second element as well so just to be really clear here this is typescript syntax I can use this exclamation mark here and I can use this typecasting here because we are in a dot ts file we are in a types could file we will compile this to JavaScript this would not work in vanilla JavaScript this is not available there with this we are forced to be clearer about our intentions and to really think about our code and double-check it which is great but that's not even the biggest advantage the biggest advantage is the addition of types that is what gives typescript its name after all and here I'm not saying anything about the types of data this function operates on if we hover over one of these parameters we see this anything here and in the end this is typescript saying to us I don't know what's in there it could be any type of value now we can add a more explicit type in typescript files so not in JavaScript files but in typescript files by adding a colon here and then specifying the type for example number doing this here and doing this here with this extra syntax which typescript which this compiler understands we're telling typescript that this year will be of type number and this will be of type number and therefore now we get an error here again and we don't just get this error in the IDE by the way we also get it if we try to compile this code because that is ultimately what we need to do right now to compile this I will open a terminal and here I'm just opening my terminal or command prompt which is integrated into this IDE it's the regular system command from the regular system terminal I was using here as well just already navigated into this folder so if you are not using some built-in IDE terminal you can use your regular one but CD navigate into that extracted starting folder where you added your type script file and once you are in that folder you can run TS c that will invoke this typescript compiler we installed earlier on using - TS TS and if you run this you will actually get an error you will still get a JavaScript file because by default typescript will still compile it to JavaScript you will also learn how to suppress this later in the course but it gives you a compiler error while doing so it tells you that argument of type string is not assignable to parameter of type number so the problem here is that typescript understands that what we get on the value property of our input element will be a string we also see this here in the IDE and we can't pass this to add because there we don't want a string we want a number so we have to fix this by for example converting this to a number here by adding a plus and as soon as we do this we can compile this code again by repeating that command and now it compiles without errors it gives us this using typescript our javascript file and now it shows some errors again because it doesn't understand that I will never use both files at the same time here again this is also something which will get better later in the course once we configure this we can ignore this for now so it gives me this file and if we open this we see something interesting in here we see that there of course our types are gone this casting here is gone we have vanilla JavaScript again so if we have a look at our types code file here we see that there we have all these nice additions but as I mentioned these are just types with features when you compile to JavaScript they are used to evaluate your code and to find potential errors but then they are stripped out and we get regular JavaScript as output so now we can go to our index.html file and import using T SJS and that's important always import JavaScript files because the browser can't run typescript we need to import the result of our compilation and now with that if we reload this we have our working code because now we have proper JavaScript code where we fixed this issue by casting our inputs before we pass them to the function but we were able to fix these issues because of our type annotations here and as you saw we had to write some other parts of the code in a cleaner way as well and dad is white typescript is amazing it forces us to write better cleaner and less error-prone code so you saw typescript in action and it offers great advantages it makes writing clean code really easier typescript adds types and data is super important with types we have to be way more explicit about how things work and we can avoid many unexpected and unnecessary errors by using types in addition to that we also can use IDE s modern IDE s which have built-in types of support which can pick up on these types and give us better order completion and built-in errors which show before we even compile the code because they also understand typescript but besides the types and the huge advantages we get alone by using types we also get our features added by typescript we can use certain next-generation JavaScript features which you can write and use in our typescript files and then they will get compiled down to JavaScript code to workarounds that even work in older browsers if you know Babel which is a tool that allows us to do that with vanilla JavaScript as well it's a bit like that just already built into typescript we can use modern JavaScript features and still produce and ship code that works in older browsers as well types could also add certain features which only times could understands like interfaces and generics these are features which can't be compiled to JavaScript but they don't have to because they are features that help us during development that give us clearer errors and help us avoid even more errors so it even adds more features on that front besides the types we already learn about it also gives us certain meta programming features like decorators on which I have a whole module in this course where you will understand what exactly decorators are why they are so meta and why they are amazing typescript also is highly configurable we didn't configure it thus far but I have a whole module in the course where we talk only about the compiler and how to configure it and you can really find unit to your Harmons to make it stricter or looser and to ensure that it behaves in exactly the way you want it to behave and with modern tooling with modern itës you even get support in non types good projects the IDE you just saw Visual Studio code that even gives you better support in plain JavaScript files because it is able to use some types good features under the hood without you explicitly using typescript so that's a free gain you get out of the box when being aware of typescript and when using modern tools so there are many reasons for using typescript and that's probably why you took this course in this course we will now learn it step by step and we will learn all about the amazing features it adds this course is packed with content we're almost done getting started and thereafter we'll dive her right into typescript and into all its exciting features and learn them step by step we'll start with the typescript basics of course the core types how it generally works some of the new features it adds and all you need to know to get a good understanding of typescript thereafter will already dive deeper into the typescript compiler and the configuration of it because it's super important for you to understand what you can configure there and what all these different settings do is it will have a closer look at that in this module thereafter we'll explore next-generation JavaScript features supported in typescript how are they work and how you can use them in typescript will continue with classes and interfaces a super important concept partly also in vanilla javascript in the case of classes but with interfaces we also get a brand new typescript feature and you will understand what they are what they do and why we might want to use them there after it's time to dive deeper we'll have a look at some advanced types and advanced types good features in general taking it to the next level there and building up on the basics we already learned about up to this point also an advanced feature which definitely deserves its own section is the generics feature you will learn what that is and why it's really really helpful in this module followed by decorators decorators are a pretty cool feature also added by typescript and we'll have a closer look at decorators and also build some really useful decorators in that module and thereafter we will have learned a lot about typescript now the course is organized such that I show all these individual features in relatively small simple demos now to also give you a bigger picture and to see how you would apply all these features in a real project we'll build just that we'll have a whole module where we built an entire project entirely with typescript from scratch so that you see many of these features most of these features you learned about up to that point in action and you see how they work together and why they simplify the process of building such a project once we're done building this project we'll identify a new problem and we'll learn how to solve it by working with namespaces and modules which will help us make our code more manageable and readable building up on that we'll also explore webpack with typescript webpack is a build tool we use in modern front-end web development and you can use it combined with typescript to get a better project setup which simply make certain things easier and allows you to get the best of both worlds a great development experience and all the code that works really well for your end-users once we're done with that we have a very solid picture of typescript and how to work with it in project now what you will need in a lot of real projects are third-party libraries so we will take a closer look at that because there are certain third-party libraries which really embrace typescript and have built in typescript support but there also are many libraries which don't and we'll have a look at how we can work with both types of libraries in a great way in typescript project well and then there are some specific scenarios which deserve their own modules we'll have a whole module about react with typescript how you can build an entire react application with typescript only and also an entire module about node.js and Express and typescript so that you also have great examples for these very popular and specific use cases of typescript where you can suddenly create react or node applications in a brand-new way with a brand new language so lots of exciting content in the course let's not waste any time let's see how you can get the most out of the course and thereafter let's dive in your success matters to me and I want to ensure that you get the most out of this course now of course that starts with watching the videos this is a video on the Monde course self course watch the videos you can go through this course step by step it's built in such a way that all the modules and lectures build up on each other you can also skip certain modules of course because all the modules all do work on their own if you already know a concept for example now when watching the videos of course do that at your speed you got speed controls here in the video player and you can slow me down if I'm going too fast or speed me up if I'm going too slow for your taste I also recommend that you code along it's not a must-do but you typically learn better if you write code on your own and you have to find and fix your own mistakes all the pause and rewinds the videos for that because the videos are of course recorded in a way that also makes sense to people who are not coding along so if you do you might need to pause occasionally try out the next steps on your own or go back to an earlier point in a video to see how exactly I implemented something there and in general practicing is important in this course we work on real projects and we have many smaller demos and I can only encourage you that you sometimes pause and try out the next steps on your own or that you deviate from what I do and try out your own things so definitely also advance on your own of course only to a certain extent because if you haven't learned about a certain feature it might be hard to implement it on your own but whenever possible whenever you feel like it definitely try out things on your own now when you do that or when you just code along as well you will also face some errors things don't always go as planned you introduced a mistake in your code and you get an error now debug these errors and search on your own use the attached code which you find attached to many lectures in the course always to the last lecture of each module so that you can compare your code to mine and find out where it deviates but also if you get air messages google them or use the search here on udemy to also search the Q&A section because chances are someone else had a similar error and you can quickly fix it by looking at their solution now of course if you're really stuck or if some concept is unclear you can also ask but also answer here in the Q&A section I do my best to provide quick support there but also try to help others there on your own because besides fixing your own errors if you also help others and work with our students you get a lot out of this course as well so that's definitely all the recommendation I have and with all these steps or all these building blocks you have everything you need to get the most out of this course now in the next lecture I will show you the the setup the ide i will be using throughout this course and thereafter we can already dive into typescript typescript is amazing but in order to work with it efficiently I strongly recommend that you also have a powerful code editor a powerful IDE and here my clear recommendation is Visual Studio code it's free to use and it has amazing typescript support built-in now you still need to install the types of compiler and we already did this but this has the built-in support which shows you a lot of errors directly in the IDE before you even compile the project so you can simply visit code Visual Studio com and there you can download it for any operating system and simply walk through the Installer there to get this modern IDE now it is the IDE I will be using throughout this course and you can fine tune and configure it to your requirements and needs here are just some settings I'm using under code references you can change the color theme and there I am using the dark plus theme so if you want the exact same look that's the theme I'm using but of course you can also play around with any era theme here I also installed certain extensions so third-party plugins so to say which change the appearance or behavior of the editor you can click on View and then extensions to be taken to the extensions menu or the marketplace and it's all free no worries nothing here costs you money now I got tons of extensions installed but the extensions I would recommend that you definitely have a look at is es lint that you install this to get linting to get code quality check support in your projects and that you install the material I can seem if you like these file icons I have in my projects that's a pure visual thing of course it doesn't change any behaviors and I can all recommend path intellisense so that later in the course once we work with imports you get better support there and prettier which helps you format your code so that it always looks nice and is readable prettier works together we'll insert the shortcut which you should be aware of under preferences keyboard shortcuts dear if you search for format document this shortcut here is a shortcut you can always press in your code to auto format it to add missing semicolons to make sure you use the right indentation everywhere things like that it makes your code more readable in your life as a developer easier and that's it you can also install TS lint but that will be merged with es lint in the future so es lint should be all you really need with that we can go back to view Explorer and you should have the same settings I have here but also dive into the settings in general and explore them and find you everything to your needs and to your likings and with that you have a great editor which allows you to write great code powerful code with a lot of built-in types of support and you're well-prepared to get the most out of this course so we set up d ide which is important now let's also set up a starting project which we'll use throughout this course in the different course modules so basically a project setup with which we can start every course module to then write our code there now as you will see throughout this course writing code doesn't require a complex setup in general but here I want a project where we can write code compile it and then immediately see the output of that code in the browser and for that I'll first of all add a new index.html file and you can add this in any empty folder the two other files or folders you see here are just config files for git in case you're using version control and for my editor which sets the zoom level so that's all I have here but in that index.html file I will now initialize it with a base skeleton and for that and visual studio code you can just type HTML choose that html5 option if you're not getting this menu just press ctrl in space choose the html5 option and hit enter and we'll get this skeleton there we could enter understanding typescript here as a title but that does not matter too much more important is that here you add a script tag in your head section and add a source and point at app J s here and add the defer attribute this tries to import a app.js file which of course right now doesn't exist and it will then of course also execute it if it finds it this allows us to view our changes our code changes directly on the screen in the browser or if we're just logging something to the console in the browser dev tools next I will add an app dot ts file that's the file a typescript file where we will write some code and there for example you could console.log your code goes here or whatever you want you can console.log whatever you want here and if you do that you can compile this file with typescript which we installed earlier for dad you can open the terminal integrate it into the editor here and simply write TSC ts this compels this types would file and generates a app.js file now which is the file we're importing here and if you now open this index.html file you see whatever happens in here you kick off the logic you wrote in here and either that's logic that manipulates something on the Dom or like in this case it's logic which simply gets locked to the console so here in this case I opened this HTML file in the browser you can simply double click on it outside of the IDE so in the normal Windows Explorer or the Mac finder and then maybe open your developer tools if you're just logging something to the console and you'll see your log here now that's nice but whenever we change something here in our code we have to manually recompile well that is what it is for now it will change later in the course but we also have to manually reload this page here and to speed this up and make sure that you don't have to do this whenever you change something we'll actually also add another tool here to this dummy's setup which we'll use throughout this course so that this happens automatically now to install such a tool let's run NPM in it here in this project folder the NPM command is available if you install node.js make sure that for that you visit no trace org and download and install the latest version you find here for the moment we're not going to write any node.js code but no trace comes together with the npm tool which we can use to install third-party dependencies or useful tools that speed up our development and for that reason we need it here so with that installed you can run npm init in this project folder simply it enter and you can answer all these questions here with the defaults by simply hitting enter all the time and once this completes it gives you a package.json file which looks something like this and now you can run npm install to install a dependency which is exclusive to this project so to install a tool you could say which you can use in this project - - save - death - mark it as a development only dependency so a tool that helps us during development and does not contain any code which will execute as part of our main code and the tool name is light - server if you hit enter here this installs this extra tool and once this finishes just go into your package of JSON file and in the scripts part add a comma and add a new script which you name start and then as a value between double quotes enter light - server so that name of the package which was added here if you now it enter you can run NPM start here to start this start script and Lite server is a simple development server which always serves the index.html file next to the package.json file so this file and it serves your application on this URL you see here localhost 3000 by default and you can then just visit this location simply enter localhost colon 3000 in the browser and now your code runs here and why is this better well this will now automatically reload the page whenever another file in this directory changes so if I for example add an exclamation mark here and I save this and I then compile this again with TSC app dot TS and you go back to the browser you see the latest output immediately because it automatically reloaded and that simply saves us the extra work of reloading manually now important about this NPM start process definitely keep it running as long as you are working on your project as long as you are writing code which you want to see execute in the browser once you're done you can always quit this process with ctrl C but once you do so your project is no longer getting served under localhost 3000 so keep it up and running as long as you are writing code and making changes with that I'll change it back but this is totally up to you and this is the project setup I will use throughout this course you also find it attached of course in the finished form just one important note if you download the attached starting project or any other course snapshot any other code snapshot you find anywhere in the course then you will get a download that does not include this node modules folder this is a huge full which Indian stores all third party packages and their dependencies and since it is so huge I typically delete it because you can easily recreate it by running NPM install so if you download one of my attachments navigate into the extracted folder and in that folder run npm install and this will install all the penances and recreate this node modules folder and once you did this you can run NPM start or do whatever you want to do in this project and was dead we got this project set up we'll use throughout the course now let's not waste any more time and let's just get started now with the core basics or with the getting started section out of the way let's dive into the core type script syntax the core features and that of course means we'll dive into the types which types types with offers and supports and how we work with these types how we assign types how we can reap the benefits of using types and all that fun stuff typescript provides many types to JavaScript now javascript itself also knows some datatypes and I'll come back to that in this module as well but typescript adds many more types and as you will all learn in this course typescript also enables you to write your own types now let's start with some of the core types which javascript already knows and which typescript all the supports and we'll also have a look at what the difference between javascript knowing the type and typescript using that type means one of the core types we work with and JavaScript and typescript is the number type now in JavaScript and the same is true for a typescript there is only one number type there is no special type for integers or floats instead these values here would all be numbers one would be a number without a decimal place 5.3 obviously is one with a decimal place and all these values are of type number other programming languages have special integer types and float or double types javascript doesn't have that and types good doesn't have it either so we have the number type which we know from JavaScript also as a type in typescript we also have two string datatype and that would be text which you can define in one of these freeways with single quotes with double quotes or also with backticks the last notation with backticks is a special syntax provided in modern JavaScript and also in typescript which allows us to write so-called template literals that are normal strings where you can dynamically inject some data into them and so strings are simply text and JavaScript knows about string value types typescript does so as well last but not least one of the core data types javascript knows and typescript also supports is the boolean data type that would be true or false and that's super important in programming obviously especially when working with if statements here we got these two values and that's important because in JavaScript you also might know this idea truthy and falsy values for example debt zero the number zero is a falsie value if you use it an if condition it is treated as false the boolean data type really just knows these two values though true or false and that's not just a case for typescript but all of our javascript this truth the false ii concept which you should know that is not related to data types that some behind the scenes work javascript as at runtime when it sees certain values in if conditions so with numbers strings and boolean z' we get a couple of core data types of course not all we got objects and so on as well but let's focus on these types and see what typescript does with them or what we can do with them with the help of typescript for this i'm back to the project we saw in the first course module and there I showed you that all you need to do now is run NPM start in a terminal navigated into this project folder to spin up this live development server which will reload whenever we change something and here I opened up this localhost 3,000 address in a new tab off my browser right now I'm getting an error because I have no app trace file yet of course you find this starting project all that hatched to this lecture will get such a app.js file which we're trying to import here in our index.html file as soon as we compile apt yes from typescript to JavaScript and we can do that in a new tab of the terminal so did we keep this process running and open a new tab instead by simply running TSC app dot TS and what this does is it compiles the type good file and spits out a javascript file and once that happens we can reload this page and we get the time to get started output here so now we have this setup here where we can ride some typescript code and then compile it to JavaScript code to see what it does now with that in the types good file I'll actually get rid of the content there because now I want to dive into these core data types which I just showed you on the slide so that you understand how to work with them in typescript now let's start very very let's say we have a new function add and there we expect two numbers and one and add two and I returned and one plus and you just like that very simple function nothing typescript ish about it now we have two numbers with which we want to work that could be number one here which is say five and all the number two which is maybe 2.8 whatever you want two numbers here now obviously and not very surprisingly we can add or call the add function and pass in number one and number two as arguments to this function store the result in a new constant maybe and then to see something on the screen we can console lock the result if we do that and I recompile this file with TSC apt yes then this page should automatically reload already if not you can manually reload of course and you should see 7.8 now you might think that's not too special right this is a pretty straightforward JavaScript snippet and indeed there is nothing typescript ish about it well let's do something which will break that snippet in normal JavaScript let's say this input here is actually not a number but some text a 5 in text and if we now save that and rerun our compilation command here you'll see that once this page reloads here I get 52.8 as output and that's obviously not the correct result of this addition now do you know why we're getting this output in normal JavaScript which we in the end are executing here well we're getting this output because this is not the result of the mathematical addition but instead this concatenates this as a string because this input here 5 is a string and then javascript sees okay I got a string I'm adding something to the string well certainly this something should also be converted to a string so that overall I got a string because the first value was a string and hence what JavaScript does is it converts 2.8 from a number to a string concatenates a longer string from 5 and 2.8 hen yielding 52.8 as a string and return stat so it's not treating this in a mathematical way but instead as a string and with JavaScript as can happen now of course you might think why would I write such code I am the developer why would I make this mistake well maybe you're not the one making this mistake maybe this is getting fetched from some user input and you introduced a little bug in your code where you forgot to transform this or you're working in a team and you're having a couple of script files working together and some other developer introduced such an error it's not impossible to make such errors but it can be hard to track them down here of course it's pretty obvious that something went wrong because we have a basic script but in a bigger script you might not even immediately recognize that something went wrong here and that's where typescript can help us we can add type assignments in this function to our parameters we can tell typescript that these two parameters should be of type number and not be of type I don't care which is the default so we do that by adding a colon here after the value to which we want to assign a type so in this case after the parameter name and then the name of the type for example number would be one of the supported names besides number you also got string or a boolean but we'll come back to those for the moment we need number and we don't just need it on the first parameter here but all is on the second one so here also we can add a colon and then number and now what we're saying to typescript is hey both parameters here should be of type number passing in values of a different type is not allowed and indeed my IDE already complains here because Visual Studio code has built in typescript support but even if we would overlook this as soon as I recompile this by rerunning TS c ab TS you will see we get an error we get an error that argument of type string 5 is not assignable to parameter of type number and it even shows us where this happened and gives us the line number line 8 and it's basically showing us the same the IDE shows here so in case we overlooked it in the IDE compiling it now fro is an error and that's the important thing about typescript it only helps us during compilation it doesn't change JavaScript to work differently at runtime because browsers have no built in typescript support it can only help us during development before we compile our typescript code to JavaScript but there it's extremely useful because it adds an extra step an extra sanity check we're here we find out oh we made a mistake here this shouldn't be a string this should be a number we can fix this and we're good this is what typescript does it helps you during development it does not change your runtime code indeed here even with the default settings it compiled our error here even though it detected it during compilation and created a file which causes the incorrect result because by default types coop does not step in here later you'll learn how you can make sure that it does but by default it doesn't even block compilation still it yells at you and points at this mistake so that you can fix it and so that you can avoid such mistakes here by the way make sure you don't have a PS and app tears open at the same time you could get errors here in the IDE regarding duplicate function implementations closing two jars could file fixes this so we already see how typescript can help us during development now we also know that there is a number type in JavaScript and we can see it with the built in type of operator this is now not typescript specific this is a built-in operator and keyword supported by JavaScript we can use it to get the type of a certain value so here we could console.log type of number one and what we'll see if we do that is that as soon as we compile this so that we run the updated code here we print number to the console now we do that thanks to this output here and thanks to the type of operator and in vanilla JavaScript without typescript we could use that to all's improve our function here we could check if type of number is equal to number excuse me type of and one I mean if that is equal to number and we could also check if type of n2 is equal to number and only perform our operation here if it is and otherwise throw an error or do the opposite and check if it's not equal or if and two is not equal and if either of the two is not a number then we could throw a new error where we say incorrect input this actually would be a non typescript way of ensuring that we can't call this function with a string here if I do this now and I recompile we get our typescript error but let's ignore that for now if we rerun this we get the incorrect input which we're throwing ourselves so now we hardened this function in JavaScript it fails at runtime but failing might here be better than showing an incorrect output which we had before so this would be a way of checking the inputs in just JavaScript you don't need typescript for that that's regular JavaScript code but of course this approach has downsides sometimes it's the right thing to do sometimes you only can validate certain inputs at runtime but the downside is here we're checking something which we actually can avoid during development with typescript so yes we're throwing an error and in our application we might have built-in measures that can then fall back to some other behavior to save the running application but still we're throwing an error which is really not necessary to occur in the first place we could have prevented it with typescript and here we really see the difference between JavaScript and typescript when it comes to types javascript is dynamically typed which means it's perfectly fine that we have a variable which initially might hold a number where we later assign a string to it and that's why we have the type of operator so that we can check the current type of something at runtime if we have some code that depends on a certain type typescript on the other end is statically typed which means we define the types of variables and parameters ends on during development they don't suddenly change during runtime now of course since typescript is compiled to JavaScript they theoretically could but if we use typescript and we write code where we suddenly assign a new type of data into a variable where we previously set that this should be a number for example and now we're assigning a string then we get an error during development so that we are forced to be clear regarding the types something can or cannot hold that's the difference here so we don't really want to use implementations or solutions like that if we can avoid it with typescript still it's important to know that javascript of course knows about the concept of types it knows about some types like numbers string and boolean but using that always means that we can only fail at runtime instead of during development which is a better place for us as a developer it allows us to fix bugs earlier and in addition javascript only knows about a couple of types as you will learn throughout this course typescript knows about way more types than JavaScript so this runtime checking is really not as flexible or not as powerful as what we can do with typescript and for all these reasons this approach is actually not the approach we want to use here sometimes it can be useful to get the type at runtime but sometimes like in this example it's way better to get it during development the only important thing to recognize of course justice that with typescript you only get to support during development not at run time because these typescript features and checks are not built into the JavaScript engine so that logic can't execute in the browser it can only execute during development when you compile your code so now that we know about typescript fundamentals and how it differs and also is related to JavaScript let's dig a bit deeper into the different core types typescript knows the number is the type we see here and as I explained there is no difference between integers like the 5 here and floats or doubles as it would be called in other programming languages like the 2.8 here indeed in JavaScript and the same is true in typescript all numbers are floats by default so for JavaScript and therefore all for typescript there is no difference between 5 like this and 5 like this it's the same number essentially now besides numbers we also have other core type and that would be strings so text and boolean let's also have a look at those we actually saw all of those in action here in this if statement already which we learned is a bit redundant nonetheless this here would be a string also of course 5 with quotes would be a string because it's text and the result for example of this comparison here that would be a boolean this operator the triple equal sign or the negated equality operator here that produces true or false and of course we can either produce it dynamically in AF check which will often do or we initialize a variable with a true or false value so let's do both here here we could add a new constant print result and set this to true for example and just to make it really clear this could be a variable as well it doesn't have to be constant variable which you would create with let in JavaScript but since I don't plan on changing it here I'll go with a constant and we could pass this as a third parameter let's say we pass in print result which holds true here now we immediately get an error of course because our add function does not support a third argument we see expect the two arguments but got free so therefore we have to make sure we support a third argument and there we could add a show result parameter you could name it print result here as well I'm going with show result to a white confusion regarding the naming but technically these two names would not clash so here I'll name it show result and I want to make sure that this is of type boolean by setting this to boolean again by adding a colon after the parameter here and then by adding the name of the type now this function accepts this it now what we can do is we can add a if check here and check if show result if this is true we can of course compare it to true but as you know in JavaScript you can also just pass in the truth or false value here and JavaScript will evaluated and if this yields true somehow or a truth D value in general then we'll make it into the if block otherwise we won't and let's say we do make it in here and then I want to console.log + 1 + + Q otherwise in the else case if we don't make it in there then I want to return this so now this is a function which sometimes returns a value and sometimes does not return a value but output it immediately now you could argue if you want to write such a function which is kind of unpredictable or which might behave unexpectedly if you're passing and true here but here we're doing it so this function only sometimes returns sometimes it also does not return but instead just lock something to the console now here we can actually call add just like this and don't need to store it in result and don't need to console.log result because with print result set to true add itself so the function itself will print a result hence if we now save that and we recompile our app ts file here with the TSC command once this is done the page will reload and we still see our output here but now it's coming from line 6 and if we have a look line 6 is indeed inside the function so this is a boolean now let's say we want to customize the output and therefore we have a result phrase constant here where we say result is : and then some white space and we pass that in as hoo as well with result phrase here well then we could expect this as an argument here as well phrase which should be of type string by adding a colon and then string is the name of the type and now we could use that phrase to output it as part of our result output if we're printing the result right in the function so then here we could have phrase + + 1 + + 2 and if we do that and we recompile by repeating that command will see that this phrase is part of the result but we also now reintroduce the old back because I have a string which I combined with two numbers everything is converted cue a string here and that's not what I want to avoid this in this function we could add a result variable here or a result constant and store our result here this will now be treated in a mathematical way because only numbers are involved and then here we could combine that with phrase or just return it and now since this is never directly calculated together with a string this will always be a number and yes then here this number combined with a string will be converted to a string but since the mathematical calculation finished before that will have the right result so now if we repeat that and a recompile we get the right output so now these are the core data types in action let's now make sure we fully understand how types are assigned and also why we don't explicitly assign types down there so we're using the core types of number boolean and string and here in the list of parameters of this function we're always explicitly assigning the types with a colon after the parameter name and then the name of the type so here the names are number boolean and string and in case you were wondering these are now special identifiers this overall here is a special syntax which is added by typescript it's not part of the compiled JavaScript code if we check that code here these type assignments are gone because javascript does not support them this colon thing after a variable or after a parameter and then number and boolean and string these special keywords this is introduced by typescript the typescript compiler understands it the IDE here supports typescript and therefore doesn't complain about these special keywords javascript does not understand this syntax it doesn't understand a colon after a parameter where a colon after a variable and then the special number or string keyword javascript doesn't understand this and therefore this is not part of the JavaScript output it's really just used by the types of compiler and then well it is a compiler because it converts this code to JavaScript code sidenote you also see it switches Const but that's something I'll come back to later so we have our explicit type assignments here and it's only understood by typescript great why don't we have them down there I don't have explicit type of assignments here and by the way also not here when we calculate the result for example because typescript has a built-in feature which is called type inference this means that tile script does its best and it does a pretty good job there to understand which type you have in a certain variable or a constant and here for example it understands that number one will always be of type number in the end because you initialize it with a number now this actually is a constant so it's even more specific than that and the type it identifies here is not just any number it's the number five because you'll not be able to assign a new number or a new value to a Const value anyways if you would change this to a variable so if you would use let instead then of course this would not break anything we can use a variable there it might not be best practice because this value never changes but it's also not horrible but now if we hover over this we see typescript doesn't say okay this has to be a five but still it detects that the type here is a number now we absolutely could write this code here on our own we can add a colon after the variable name on the left side of the equal sign and then the name of the type so basically the same we did in the parameters of this function but this is redundant and it actually is also not considered to be a good practice because typescript is able to perfectly infer this type from there so assigning this is not a good idea this only changes if you would create this variable in an unassigned way like this if you don't initialize it immediately then it's a good practice to tell typescript which value will eventually be stored in there so that when you later assign a value to it and of course it's a bit redundant here to split this in two lines I'm just doing this for demo purposes but now if I assign this here this works because I told typescript in advance that this will be of type number you don't have to do that it also works if you don't do that but now you could also add this five and you wouldn't get an error because you're not telling typescript anything about the type which will be stored in this variable and therefore types could allows any type if you instead add : number here you're telling typescript hey eventually a number will be stored in there and hence if you later store something else in there like in this case where we store a string you'll get an error here in the IDE and of course also if you compile your code you will get the error we already saw before so this is how you can assign types now even if types could just infer the type and let me fix this it will yell at you if you break that inferred type actually it's wrong to say even because of course it does why would it not do that type inference is there for you to save you code to avoid that you manually have to assign a type of course typescript yells at you if you then use a wrong type a type that it did not infer for example here if result phrase is created with let so that it's variable then type could here and first that this will be of type string because we initialize it with a string so this is basically the equivalent to not initializing it and setting the type on our own and then assigning a value later now if we change result phrase queue let's say zero here for whatever reason we might want to do that well then we get an error here that type 0 is not assignable of type string and that makes sense right typescript inferred that we wanted to store a string we're now trying to store a number we get an error that's the job the core task of typescript checking types and yelling at us if we're using them incorrectly let's take deeper into the core types typescript supports the next type that's interesting is the object type now you note objects in JavaScript they look like this you have curly braces and then you have key value pairs in there and such values would also be treated as object types in typescript so any JavaScript object is of type object though I will already say there are more specific versions of objects in typescript so that you can say this is not just any object this is an object which has to has these properties or which has to be based on this or that constructor function but we'll get there step by step to dive into objects I'll first of all rename app TS here and I'll rename this to basics TS here and add a new app TS file which will then overwrite the old app.js file once we compile it where we can now type into objects and let's start by creating a basic object here let's say a person with curly braces here and we give this a name here I'll go with Maximilian because it is my name and the age of 30 now of course we can console.log her sneer and if we do so and we compile this unsurprisingly we should see that object being printed here in the console now what we also can do in JavaScript is we can try to access let's say nickname a property which does not exist here now you immediately see the typescript is not too happy about that and hence my IDE tells me it tells me that property nickname does not exist on that type so if we save that and I try to compile that we indeed get that same error down there the typescript compiler does not like this and it tells me that we have no nickname property on this object it finds out that we don't have this nickname property because if we hover over person it inferred we can see there is a colon after person so after the variable or constant name it inferred that this is the type of data which is stored in there now that's not just object as you can tell that is a concrete object it's an object with a name key where then the type in turn has to be a string and the H key where the type has to be number and actually this can be confusing here this here obviously looks like a JavaScript object curly braces key value pairs well the first important thing to see here is that we have a semicolon here after each line we don't have that in a JavaScript object we have a comma here and indeed this is not a JavaScript object here which is created somewhere this is the object type inferred by typescript and object types are written almost like objects but of course we don't have key value pairs there but key type pairs object types are there to describe well the type of object that is getting used somewhere we could be more generic I could explicitly assign a type here to the constant of object object is one of the built-in types just like number and string and now if I hover over this we see persons of type object and now typescript really only cares about the fact that this is our object type now still if we compile this we get that error though because typescript still analyzes our code and sees that we try to access something which doesn't exist there but it's important to understand that it all starts with this most generic object type but often you want to be more specific than that you don't just want to work with that generic object type you really want to get the full support for example right now if I add a dot here and I have a look at my auto completion I get no help there at all but my IDE reason for dat is that all we tell the IDE is that we have a value here in person which is of type object indeed now we actually also get an error if I try to access name name exists here right but what we tell typescript here is that we just have an object where we don't give any our information to typescript so actually typescript doesn't support any type of property because we don't tell it anything about the object so we should be more specific and we are more specific by setting a specific object type the thing which types would also inferred automatically we do this by adding curly braces here after the : after our Const or variable name so this year does not create a new JavaScript object this will actually be stripped out of the compiled JavaScript code instead this is just type scripts notation of a specialized object type so to say so all the object type where we provide some information about the structure of the object now by assigning just an empty pair of curly braces as a type we essentially do the same as with object we tell typescript that this is some object now we can be more specific though we can add key value entries here however not key value but key type instead so here we could say the object which should be stored in person should have a name property and the value of that name property should be of type string so here we described a type of value which will eventually be stored a name now by the way you see I'm getting an error here because what I'm telling typescript now is that my person should have an object with exactly one key value pair where the key is name and the value of that key is string but we then assign an object with two key value pairs name which holds a string that is fine but age which holds a number and that would not be fine so here we have to adjust this by adding a semicolon and then adding an average key value pair here where we say age should be of type number so not 30 here that actually would be supported in typescript that we restrict it to one specific number but then we'll run into issues as soon as we changed that in steps here I just want to say age should be some number and now we basically are explicitly assigning the same typescript inferred before as you learned that's not a good practice but to understand object types I wanted to do it here still this is something you can do it's better to let typescript infer this as we did before like this just to show something interesting if I switch back to the SAP optimal code where we explicitly assign a type typescript would be able to in third if we compile this code of course it works we can access the name property but if we then have a look at apps yes we see this type assignment is removed here and that of course should be something expected as I mentioned types and type assignments are not part of JavaScript they're typescript only I just wanted to show this again to make it really clear that this syntax here is not creating some JavaScript object which is somewhere in our code this is just type scripts representation of an object type that helps typescript understand the objects you're working with the batterer syntax of course is this syntax as you learned now besides objects we also have arrays in JavaScript very important type of data arrays are created like this in JavaScript as you know and you can store any data in there numbers strings boolean's objects over arrays you can have nested arrays after all and you can also mix data you can have an array with strings and numbers mixed and types with all the supports erase any JavaScript array is supported and the types often array can be flexible or is strict now let's have a look at that in typescript for that here in apt es let's say our person also has a hobbies key but of course we could also have a variable or a constant hobbies outside of the object so using arrays is exactly the same inside of objects and outside of them so here we have hobbies and hobbies could be sports and cooking let's say so I have two elements in there and these elements as you can tell our strings now if we hover over hobbies typescript correctly detected the disks of type string and rain now that's the syntax you haven't seen before but this is how typescript describes an array of data you have two square brackets and in front of that the type of data which is stored in there now this is the type typescript inferred it saw that here we have an array in that we only have strings in there so it inferred that hobbies probably should be an array of strings and indeed for hobbies that makes a lot of sense of course you can also explicitly set the type of a variable if we would add a new variable favorite activities and initially that should be empty then we might want to explicitly set the type of data stored in there and now let's say that should be an array of strings well then we can't just repeat what we just saw type string and then square brackets thereafter and this tells typescript what we store in here is not just a single string it's an array of strings and indeed if I try to store just sports in there I get an error I get an error because that here is a single string and not an array of strings I don't get an error of course if I wrapped us in two square brackets and therefore effectively I create an array I again do you get an error though if I add a number let's say because we defined this to be an array of strings now here we have a mixed array it's an array of strings and numbers so that does not work and is not supported here if we would want to support such a mixed array one solution would be to use any here the any type is a special type in type script which we'll have a closer look later which basically means do whatever you want it's of course a type you don't want to use too often because you'll lose the benefits typescript gives you your back and JavaScript world where you also can use any value anywhere so any is really flexible but the flexibility comes at the price of basically giving up all benefits types with offers so here I when I go back to string because I really don't want to have a number in there and hence we can remove the number and we're good arrays also give us a great example actually just like objects and their properties how dynamic type scripts type inference is if we add a for loop here at the bottom and we want to go through all the hobbies of person we can of course use a traditional for loop with for Const hobby of person dot hobbies so accessing the hobbies property and going through all the hobbies they're storing each hobby for each iteration in this constant and then we can console.log hobby here now that's not too fancy that's something we know from JavaScript right if I now compile this app TS file down there we get the name from this line and they're after the two hobbies being printed but what's actually interesting here is that on hobby we can access anything we can access on any string for example to uppercase I get this Auto completion and typescript does not complain why does it not complain because it knows that hobbies is of type string array so when I access person that hobbies typescripts inference detects that hobbies will be an array of strings so hobby on the other hand is correctly identified as being a string because since we go through an array of strings well the individual values have to be just strings and therefore types would offers us great support down there and allows us to do anything with hobby that can be done with a string because it knows with certainty that hobby will be a string because of the types we setup up there and that's really flexible and of course a great feature which makes writing code a lot easier and way more flexible and secure for example we would get an error here if it would try to access hobby dot map if I thought this would be an array the map method is available on a race but not on strings and here correctly I get an error that map does not exist on type string because it doesn't so here we get an error and that's good that we get it because this would be wrong and here we see type scripts and Ferns really really shine so arrays are supported and with numbers strings boolean objects and arrays we got the core values or value types javascript knows supported in typescript as you will learn at the example of objects and arrays typescript even offers way more functional he's there that's a bit more advanced which is why we'll have a look at that later but even these core types with what you learned in the previous lectures are supported now types could also add a couple of new concepts new types which we don't know from vanilla JavaScript for example the tuple type now you might know to 'pls from other programming languages javascript does not have them this is a tuple for example and you would say well this is an array it is an array but it's a fixed length array and actually not just fixed length but also fixed type and where could this be handy let's say here on our person we actually have another property role which is an array with exactly two elements where the first one is let's say a numeric identifier like 2 and the second one is a string identifier and a human readable description like author now this should always have exactly two elements because a user or a person in this application which we're writing let's say can only have one role and a role is only made up of two elements of course we could have used an object here but for some reason we want to have an array with exactly two elements where the first element always is the numeric identifier and the second element always is the string identifier or description or however you want to call it now if we hover over this typescript actually infers this strange type which we haven't seen before in fact of it this means typescript understands that we have an array which might hold eber strings or numbers this is a union type and we'll dive into those later the key takeaway is the typescript understands that this should be an array with these types of values the downside is that we could run this code though purse roll push admin now for our application this might not make sense because we know we only need two elements still typescript doesn't know that we only want two elements we would also be able to switch person role the second element with index one to be a number as well this would work because typescript only knows that role should be of type string or number array and they are for assigning a number here to the second element and therefore replacing it with a number would be allowed because we're just saying something about the types we generally can use in there we know we want to have exactly that structure two elements first element number second element string but typescript doesn't know that well for such a scenario a tuple would be perfect we can tell typescript what role should be by explicitly setting the type of role so here we also have an example where typescript does infer a type but we explicitly want to override it now here we can therefore add an explicit object type by adding a colon after person then the curly braces and then name should be a string age should be a number and hobbies should be a string array so all as inferred by typescript so for Dada we wouldn't have required this explicit assignment and as you learned it would have been bad but now we have a scenario where the inference does not work in the way we want and we want to set role to be a tuple now instead of setting a two string array or a number array we're using the same type that was inferred here earlier we can now use a special type we use square brackets again but now inside of the square brackets we add number and then a comma and then string now this marks a tuple type here a tuple is a special construct types could understand in JavaScript it will be a normal array but during development with typescript we'll get errors with code like this year and what do tuples do this year tells typescript I want to have a special array with exactly two elements because I have exactly two types in there and the first element should be a number the second element should be a string hence if we compile this code here I get an error regarding 10 not being assignable as a type here because we want to have a string as a second value and if I then assign 10 as a second value here then I obviously don't follow this rule now if we comment this out and we compile this works that's a bit strange because why does pushing Weirich here because we're also saying that roll should have exactly two elements so why can we push admin onto the role array here Porsche actually is an exception which is allowed on Hugh bolts so unfortunately typescript can't catch this error but at least it ensures that we're not assigning a wrong value here and outside of push we also get some support regarding the length if we set person to roll to a new value for example an empty array is not allowed one with exactly the structure we defined up there is allowed if I added an extra element here then we would again get an error so the length is enforced if we assign it like this but not for a pushing and so on this is something you have to be aware of but still getting this support and this support is pretty nice and if you have a scenario where you need exactly X amount of values in an array and you know the type of each value in advance then you might want to consider a tuple instead of an array to get even more strictness into your app to be even clearer about the type of data you're working with the type of data you're expecting loosely related to the idea of a tuple is the idea of having a couple of specific identifiers global constants you might be working with in your app which you want to represent as numbers but to which you want to assign a human-readable label and for that you have to enum type again that does exist in some other programming languages javascript doesn't know it though it looks like this this is how you create an enum you use the enum keyword which only exists in typescript world not in JavaScript then after you have curly braces and then your identifier and this type which is added by typescript gives you an enumerated list so these labels are in the end just translated to numbers starting at 0 where you have human readable labels you can work within your code to show you an example let's go back here to our person with its role I'll copy that code and then comment it out because I'm going to change it a bit and then here I'll get rid of that explicit type assignment and instead go back to inference because I'll now change role and now let's say we want to have an admin and author and maybe a read-only user the admin should have an idea of SERO read-only user has one author has two now of course we can store that exactly like this with these numbers one downside is that we can also add a number for which we might not have a role and if we then later in our code try to extract a role and use an if check this might lead to errors and in addition we as a developer have a hard time to understand which role this user has was to the author or was addy read on the user you might forget this after making longer pauses when working in bigger teams and so on so as a developer you might want human readable identifier something like admin and read-only user something like that now of course we could use that we could work with such string values the problem is if we then later needed an AF check we check if person dot roll is equal to was it read-only user or was it one word was it with others scores you see then we have to remember how we wrote these strings which exact text we have in there because this string with the dashes between the words is of course not the same as this string so here we would never make it in there is read only if we try to compile and print that because well the check simply doesn't yield true we don't have that as a roll on person hence we don't get the output here in a console so string identifier is all to have downsides now for such scenarios it's quite common in JavaScript to define global constants for example admin which can hold certain values like numbers or strings both as possible numbers of course can save us some extra code and bits in memory and there we might have admin read-only an author like this and down there we then just have to use that role now the advantage of that is that we can use this everywhere in our code and therefore here for example if I run this code if I compile it and then we let this reload we see as admin here so this works and this is a common pattern in JavaScript downside is that now again role is inferred to be just a number so we could store any number in there even a number which we don't support and in addition we have to define all these constants we have to manage them this is where enum can save us work this is totally fine but an enum makes it easier we create an enum with the enum keyword we can name it role convention is to start with the uppercase character because enum also is a custom type it's your first custom type you're going to write many more in this course this is the first one and then after the name of the type you want to assign to this enum you add curly braces just like that no : no equal sign just curly braces after the name then a semicolon and now in here you can assign your values like admin read-only and author and behind-the-scenes this year receives the number 0 this year number one this year number two and then here you can access role dot admin like on an object you access your identifier and you can use that anywhere else in your code as well here we can check if the role is author and then print author and of course we shouldn't see that if I run that now because we assigned a role of admin here but key takeaway is that we did all of that with the help of the enum which assigns labels to numbers if we have a look at that in JavaScript so in the compiled code we see this is how its rebuilt in the end it's rebuilt with if a year so a function which executes itself and role here simply is managed as an object in the end which has an admin property a read-only property an author property where we then store our number values here you could say so it's a bit more complex than that but that's what typescript in the end does here to replicate this enum construct in JavaScript code when it compiles the code here as a developer we simply have these conveniently created numbers if you hover over them you see the number which was stored in there and you can use these numbers here in a human readable way now for enums you're also not restricted to the default behavior let's say for some reason you don't want to start with zero as a starting number then you can add an equal sign here after your identifier and enter any other number and now admin is assigned to the number 5 and the other identifiers after the identifier where you assign a value pick up on that and simply increment this starting value so now we have 5 6 7 instead of 0 1 2 you of course also can assign your own values to all these identifiers so if you need your own numbers you're also not restricted to numbers you can also go with text here or even mix it like I'm doing it here anything goes there but often the default of incrementing numbers that start at 0 is what you want but if you need a different behavior if you wanna use a string in here and then a number here and you hear a number as well or maybe another string then you can absolutely do that the advantage is you define it up there and then thereafter you always just refer to your role type to this custom type you create it to discuss Tim enum you create it and you use that and your F checks and your type assignments and you're good that's the power of the enum and it's a great construct whenever you need identifiers that are human readable and have some mapped value behind the scenes with that we're almost done with the core types there is one more type which we already saw and that's the any type the any type is the most flexible type you can assign in typescript this type doesn't tell typescript anything it basically means you can store any kind of value in there we got no specific type assignment typescript will basically never yell at you when you use any back in our code here if I would set the type of favorite activities to any would not get an error if I sell it to any array I at least tell typescript that favorite activities is an array of something so if it would store just a single value in there I would get an error but as long as it is an array I can store whatever I want in there so any is really flexible and this can sound great at first but actually it's a big disadvantage and you absolutely want to avoid any whenever possible because any takes away basically all advantages typescript gives you it gives you the same experience you have with vanilla JavaScript where you also have the any type on everything so to say any basically make sure that the typescript compiler can't check anything because if any property or any variable can store any value well then there is not much to check right so you can use any as a fallback if you have some value some kind of data where you really can't know which kind of data will be stored in there and where you then maybe are using some runtime checks like we did here at runtime to narrow down what you want to do for certain values then you could go with any but in other cases you really want to avoid any if you have a chance of knowing which kind of data you're working with be explicit about it let's type scripts inference to its job or explicitly set your own types don't fall back to any if you don't need to so we covered a couple two core types type scoop nose now let's move on for that I'll rename apt es here to object arrays enums or whatever you want to name it basically so that we still have that file but I'll create a brand new app T as file so that we have an empty file again in which we can work now in this file I want to dive into now very interesting type which you find in typescript and that's the Union type now what's that let's come back to our add function which we wrote earlier I'll copy that and move that into apt es get rid of that comment here and here on add let's close basics yes so that we get rid of that error here in add I now want to be more flexible regarding what we accept here I will also get rid of show result and phrase it don't need that and the only thing I want to do is I want to calculate a result and return it but I want to be more flexible regarding the inputs previously we made sure that we only work with numbers now let's say we actually name this combined and it should work with both numbers and strings because it turns out we can combine both numbers and strings with this plus operator the only difference is that in one scenario we get back a number as a result in the other scenario we get a concatenated string as we actually already saw earlier in this module but now I want to allow this behavior because you could have an application where you want to have a flexible combination function that does work with numbers and strings therefore I will all this input one year and this input two and combine these two now but we will have one problem of course right now we set both parameters to be numbers this means that we can call this function as long as we do want to work with numbers let's say down there we're creating a new constant combined ages and there I call combine and pass in 30 and 26 here as ages in whatever application we're building and thereafter console.log combined ages well it shouldn't be too surprising that if we now compile this file here and we then reload this page we get 56 so this works we get this number but of course we have a problem if we try to create a string here combined names for example if I try to combine Max and Ana here then while we immediately get an error here that max is not assignable to type number because this of course is a string now of course we could change this to accept strings instead of numbers but now the first function call would fail and that is where Union types can help us if we have some place in our application B that a parameter of a function or a constant or a variable we're using somewhere where we accept two different kinds of values well then a union type can help us q tell typescript that we are fine with either a number or a string we use number and then the pipe symbol here and then the other type we all accept and you can have more than two types you can accept as many types here as you need so here I only need two though and that's there for the type assignment I'll go with number or string now I get an error here that the plus operator cannot be applied to type string or number and string or number that's actually not entirely correct this should work because we can use the plus operator with both numbers and with strings but typescript only sees that we have a union type here and it doesn't analyze what's in the Union type it just sees okay you're expecting multiple types maybe that includes types where I can't use the plus operator hence I will complain here now thankfully we can work around that issue though we can add our runtime type check here and see if input one if the type of that is equal to number and if the type of input two is equal to number and then move this calculation in there now just one improvement let's create result as a variable outside of that if check because of block scoping so that this is a variable available in the entire function and then just assign a new value in there so now here we check if we do have two numbers and they offer typescript now listed in here input one and input 2 both will be numbers now let's add a else check here and there we can set result equal to input 1 dot choose string explicitly converting this to a string and input 2 to string and this will then also be fine for typescript and JavaScript because we can't concatenate two strings so now we have almost the same calculation but we make clear that here will always work with numbers here will always work with strings and then we return the result and now with that if we console locked combined names down there and we compile this file we'll see that once we revisit our page we got the combined numbers there which were simply added together and hence we get a number as a result and two combined names here so this is how we can use Union types to be more flexible regarding what we do in a function for example or anywhere else in our code this extra runtime type check will not always be required when you work with Union types but often will be because with Union types you can be more flexible in for example two parameters you accept but then you might have different logic in your function based on which exact type you are getting so that your function is able to work with multiple types of values but that it then does slightly different things depending on the type you're getting so off you might need such a runtime check when working with Union types but you'll not always need it you will certainly also encounter situations in types could programs where you can use a union type without a runtime type check it really depends on the logic you're writing so now we got union types here let's build up on that idea of union types and all the introduced literal types literal types are types where you don't just say that a certain variable where a parameter should hold that say a number or a string but where you are very clear about the exact value it should hold we saw that early already here in basics constitu for example there if I hover over that you see the type which was inferred is not number its 2.8 and typescript did infer this concrete number as a type here because it's a constant it will never change in the effort high scope knows the value I assign here is the exact type I have so of course this is a number you could say 2.8 is derived from the number type but it's a specific number and this does not just exist for numbers but also for strings and so on and especially for Strings it can be very useful let's say here in our combined function we expect numbers or strings and we combine them differently based on what we get but we also want to allow the caller of the function to define how the result should be returned so that we can basically force a conversion from number to string or the other way around we could do this with a third parameter and we could name that let's say result type or a result conversion or however you want to name it and I want to describe this with a strings all set is to type string now my idea is that I can call combined here with two numbers and for example pass in a string of as number and it's totally up to you which identifier you use here down there we might have as text but then we might have another combination here bind string ages where a pass in two strings but I still want to output this as number and this would be a case where the third parameter can be helpful to force a conversion because if I pass in two strings here normally we would make it into this else branch and concatenate it and I might want to return this as a number instead so that I can also console.log combined string ages here so now we just have to take these identifiers into account in our function by including a result conversion in our if checks now the question is what exactly do we want to do do we want to make sure that we can force these two strings to be added as numbers or do we want to force the result no matter if it was a mathematical calculation or a string concatenation to be converted to a text or a number if we want to force a conversion we could add the if check here and check if result conversion is equal to as number and if that's the case I want to return result with a plus in front of it which converts it to a number the alternative would be parse float for example but here I'll just go for the plus since this is a bit shorter and else I want to return result to string to force an output as a string so now we do the calculation based on the real type we get but then we convert the result that's one way of doing that and if we save that and we then compile this file we see this is the result I get and we get dead output for example for our string combination here because as I said the combination itself the calculation so to say is performed based on the type we feed in which here is a string so we concatenate it and then we just convert to result the alternative logic would be to check the type here and do a different operation based on the return type we're specifying here so we could come this out and instead here say if the type of input one is number and the type of input two is number or if result conversion is equal to as number then I want to combine values like this and now to avoid this error here I've forced the conversion Q numbers by adding a plus in front of each input so that each input is converted to a number and it's guaranteed to be a number before I combine them side note if you would pass in strings that can't be converted to a number so something like max for example then you'll get na n not a number as a result well in in the elds case so that we don't have as number or that we simply don't have number inputs then we make it into this block here and now with data fire return result again here and we didn't save this and recompile we'll see a different output on our page now we get 56 in these two lines here because now we're not converting the result so we're not converting they're concatenated string for this line but instead we're doing the conversion before we combine the two values so that's up to you which logic you want to implement I actually want to have a closer look at the literal types concept which I described at the beginning of this lecture I'm passing in as number and as text and the downside of this is that right now we as a developer have to memorize these values we have to make sure that we don't miss type here now we could use a enum to improve that but if we only have Q values here as text or as number then maybe also such a literal type could be an option we could say this shouldn't be any string it should be as number or as text so we use a union type combined with literal types literal types are the types which are based on your core types string number and so on but you then have a specific version of that type so here we allow specifically these two strings not any string just these two strings so we want a string for result conversion but it has to be one of these two values any other string value will not be allowed so that's the idea behind a literal type and often you will use this in the context of a union type because you don't just want to allow one exact value you could hard-coded into your code if that would be the case but you want to have two or more possible values in this case we got two possible values so now we are guaranteed to get result conversion which is either as number or as text and for example here if I now try to compare this to as number because I have a typo here typescript is able to tell me here in the IDE and of course also if we save it and compile it here in the terminal because it knows that as number without a are at the end will never be a valid value for a result conversion because I set this Union type with these literal types so now we again gain some extra type safety and ensure that we can't use this incorrectly the same of course for passing in a value if we have a type here we get an error only if we use either as number or as text we're allowed to compile this as you see if I now compile this this works and we get the same output as before here so these are literal types especially useful when used in conjunction with Union types now when working with union types like this and this it can be cumbersome to always repeat the Union type you might want to create a new type which en stores this Union type and you can do that with an average good feature the feature of type aliases you create such a alias typically before you use it so here at the top of the file in this case here with the type keyword now the type keyword is not built into JavaScript it's supported in typescript though and after type you add the name of your custom type or of your type alias I should say for example combined able but the name is really up to you you can invent any name here which is not built into JavaScript or typescript as a key name so something like date would not be allowed because that's built into JavaScript but combined able is not built into JavaScript not built into typescript so we can use it and now with an equal sign you assign the type you want to encode in your alia so to say so we could store a number here and now whenever we want to make sure that something should be a number we could use combined able instead now that doesn't make too much sense it arguably would even make our code harder to read if I use combine able down there for example this would work technically but if we just glanced over our code it's not obvious that here we want a number or a string well typically therefore you use that in conjunction with Union types so we can store a union type in our custom type so to say in our type alias and now just refer to combine able down there instead of our Union type so we have exactly the same setup as before we just have our reusable type alias here which we can use instead and that allows us to save some extra code and make sure we always refer to the same types or the same type setup when we use combine able and of course we cannot just use that for number and string we can use that for any type setup we might want to store it in an alias including these two literal types for example so for these two types here for this Union type we could also create a type alias conversion descriptor or however you want to name it and store exactly this type in this type Elias and now we can use this type alias down there so type aliases are really really useful you can encode more complex type definitions into your own types into your own type names so to say and reuse that everywhere in your code where you need exactly this type set up so that you avoid typos down there and you can simply save code write code quicker and always be clearer about your intentions for example by choosing descriptive type alias names up there time for an hour new file I'll rename apt yes here to Union aliases TS and add a new app ts file where we can start from scratch again close the other file and now in here I want to dive a bit deeper into functions now of course we already worked with functions for example here in the Union aliases file with the combined function and for example you saw that for functions you can't assign types to the parameters of functions well turns out there is a bit more you can do with functions and types for that I'll recreate my add function which simply accepts numbers not strings which does one simple thing it returns n1 + + 2 so not too tricky now as I mentioned we can assign types to parameters that's not new the function overall however has one important other type it has a return type and here the return type is inferred by typescript we can see it if we hover over add here at the end the : after the parameter list this year describes the return type of the function so the type of the returned value here I returned the addition of n1 and n2 and since both these inputs are numbers typescript is able to infer that the result of this will be a number and since we return it that the return type of this function therefore will be a number if we would concatenate them as strings here with two string for example then typescript would correctly infer that we return a string here now of course we can also explicitly assign a return type here by adding a colon after the parameter list and then the type you want to return like number this would be the same type as inferred if a for example set is 2 string I would get an error here because obviously my calculation here does not match my described return type now just as with variables it's a good idea to let typescript do its job regarding type inference and if you have no specific reason for explicitly setting the type you should therefore not set the type and instead let typescript infer the type regarding the return types though there is one interesting type which we haven't seen before and which might be brand new to you if you have no experience with other programming languages because it is a type that doesn't really exist in JavaScript it's the wide type let's say we have the print result method there we get a number argument which should be a number and in there i want to console.log num and i want to console.log it as part of a string where i say a result + num so now this will be concatenated to one long string and will be output and now i can call print result and for example pass to that the result of my add function call with 5 plus let's say 12 so i am executing ad here with two numbers and the result of that so what ad returns is then passed as an argument into print result and that should print it to the console if we now compile this and then have a look at that in our page or on our page here we see result 17 which makes sense now the interesting thing here is the return type of print result what would you guess is the return type here so maybe you think it's string because I'm creating a string in here but keep in mind we're not returning this we're not returning anything here and therefore this print result function here has a special return type void now you might know this void return type from other programming languages there you have something like this javascript doesn't really know that or doesn't really have a name for this situation typescript however does so indeed this function here has a return type of white and of course you don't need to specify your typescript inference did its job but I want to make it really clear that this has the wide return type which is why I am adding it here for demo purposes now why it really just means this function doesn't have a return statement it doesn't return anything it successfully completes its that it does its job it executes its code it does not yield an error or anything like that but it then does not return anything that's the wide return type now technically in JavaScript of course if we would console lock the result of print result here and I now compile this and we see what gets output here on the page we see that undefined is returned by that so technically and that's reinter esting in JavaScript if we use the return value of a function that doesn't return anything we get undefined as a value and as you probably know undefined and JavaScript is actually a real value a value you for example also get if you try to access a property on an object which doesn't exist so here we get white even though technically this returns undefined and now to make it even more confusing undefined actually is a type in typescript you can have undefined as a type and for example a brand new variable some value can receive undefined as a type and you'll not get an error this variable will now just be forever undefined how are useful that might be is a different question but and the find is a valid type and typescript nonetheless here you see we're getting an error and we're getting an error because a function is not allowed to return undefined technically it of course does but typescript thinks about functions a bit differently you should use void here if a function returns nothing and not undefined because with wide you make clear that this function deliberately does not have a return statement if you would say undefined here then typescript would expect that you have a return statement where you just don't return a value that's the technical difference now you see I'm not getting an error from a javascript perspective this is basically the same as this but typescript makes a differentiation here and therefore why does the type you want to use if you don't have a return statement undefined which you will rarely need to be honest can be used if you return without returning an actual value but again this is a rare use case and you could use white with a return statement like this as well you would not get an error and by default you would actually also use white in this scenario unless you really have a function that should produce undefined and you want to be clear about that but again that will rarely be the case I just want to make sure here that you understand difference between white and undefined that white is the standard which you'll use in pretty much all scenarios where you have a function that does not return a value and that you can assign it explicitly but of course types would always able to infer it like it would be able here as well I just added this for demo purposes here so you can use types for function parameters and for the return value of the function now to take it to the next level what if there also were a function type itself now let me make it clear what I mean let's say we have a variable combine values and this variable by default has a type of any now as you learned any is not that useful what I want to do eventually is I want you to set combined values equal to add so I want to store the add function a pointer at this add function in combined values so that in the end we can console.log combine values and execute combined values as a function to which I pass eight and eight now if I save that and I execute this after compiling it so if we compile this file and then we let this reload we get 16 here so that works and we would expect it to work because that is normal JavaScript code we can store a pointer at a function in a number variable and then therefore execute this variable as a function because well it points at that function right so we can execute that function through that variable the problem we have with this snippet here from a typescript perspective just is that combined values is any so if I set combined values to a number here thereafter of course we can compile this unfortunately because types could has no chance of detecting that this is unwanted word that this could cause a problem but at runtime we would get an error because obviously we try to execute combine values as a function when it actually is a number now we want to avoid this and for that we need to be clear that combined values will hold a function now first step into that direction is that we set the type here to function function is our type provided by typescript in the end and this makes it clear that whatever we store in here has to be a function therefore here I'm getting an error because five is a number and not a function and if I comment this out we can compile this otherwise we would get an error during compilation and now it is again runs as affected so that's good but it's not perfect because now we say there should be a function but it could also set combined value is equal to print result for example here and of course typescript would not complain because print result is a function but of course it's not a function that takes two arguments so again if I compile this typescript will not complain but if we reload we see undefined here and result AIDS so I don't get the result I want because I store it the wrong function in there again it would be nice if types could would tell us about that typescript can't inform us about this because all we said to typescript is dead we want to store a function in there and this is clearly the case so it would be good if we could be more precise regarding how the function should look like that we want to store and combine values and that's where function types come into play function types are types that describe a function regarding the parameters and the return value of that function a function type is created with this arrow function notation you know from JavaScript or at least close to that notation you don't add curly braces here because we aren't creating an arrow function here we're creating a function type instead now on the right side of this arrow you specified a return type of the function you eventually want to be able to store in here that should be number now with dead were saying combined values accepts any function that takes no parameters and then returns a number now that's of course not entirely what we want we want to make sure that combined values takes a function or is able to store functions that take two numbers and return a number now for that we can add parameters here to this function type we don't have to match the parameter just names from up there just the types so we could have a which should be of type number and B which should be of type number and now what we're saying to typescript is that combined values should accept any function that takes two parameters where each parameter is a number and where the function overall then returns a number and that's why typescript does not complain about us storing add-in combined values because ad is a function that perfectly satisfies this type definition but it does complain about print result because print result as it tells us here is a function of type one argument which is a number nothing is returned whereas we actually expect to get a function with two arguments where each argument is a number and we all return a number so we have a mismatch here and if I would try to compile this we therefore would get an error here of course in the compiler and we only can fix this by removing this line of code now we are able to recompile this without errors and now this runs as expected so function types allow us to describe which type of function specifically we want to use somewhere be that an expected value in a parameter for create a function with some callback or like here a variable now speaking of callbacks and function types there it works pretty much in the same way let's say we have a new function up there add and handle let's say and there we expect to get two numbers and then I also want to get a callback function here so a function which is passed in as an argument that should do something with the result then here we could generate the result of course but now I'm not returning it but instead I want to call the callback function and pass in result now for that I want to be really clear that callback should be a function so again I'm using that function type definition that maybe does not return anything but that does take a number as an argument because we're passing at a number here so the callback function the function we're passing into this function as a parameter should accept a number and now down there we could call add and handle pass in 10 and 20 and then pass in a function for example an anonymous function here so now here when we call the function this is of course not a function type but a concrete value we're passing in for this third argument so this now here is an anonymous function creating here and there we know we'll get a number maybe name it result here and that we can do with it what I really want but now if we compile this we see this lock down there 30 which is the result of our callback function which we passed to add and handle we're add and handle combines the two numbers and then calls to call back where the called egg has to meet this condition here the advantage of us defining the callback function definition here is that inside of the function we pass it as a callback typescript is able to infer that result will be a number and hence we could do anything with result here what we could do with a number without explicitly stating the type here because typescript knows result will be a number because we made it really clear that the callback will get one argument which is a number hence also if we would expect the second argument here in the callback we'd get an error because we know well the callback we expect in our ad and handle function only should have one argument so if we then pass in a callback function which takes a second argument that clearly is a mistake the only thing Toph does not pick up is if we return something here if a return result then they call BEC does return something even though we made it clear that it shouldn't return anything this however is not a mistake or a bargain type script it actually happens on purpose by specifying void here on our callback type we're essentially saying will ignore any result you might be returning here so we're basically saying in add and handle where we get that callback function will not do anything with a return type that's why you'll be able to return something here without punishment but you know because it's clearly defined here on the callback type that the callback will not do anything with the value you might return here so that add and handle inside of the function will not do anything with that value you might be returning and that's of course a useful piece of information you might expect it in here we're doing something with the value returned by the callback and by specifying this type here we make it really clear that inside of add and handle we're not interested in any return value so this does not force you to pass in a callback that does not return anything it just tells you that anything you might return will not be used for the parameters it's of course different there this is enforced because here it really matters that you know if you're passing a callback that expects more parameters well then you'll get an error or you'll not get the result you want because I only give you one result so there we can't just ignore what you might want as it's the case for the return type we can ignore that here for passing something in we're the add and handle function is responsible for that because that's where the call that gets called this is why parameters are enforced and in typescript is really strict regarding the number and type of parameters of callback functions and why it doesn't really care about the return type we're almost done with the basics about typescript and the core types there are two more types which are good to be aware of because they will matter from time to time and the first type is the unknown type for that I'll name this file your functions TS net and you app ts file and in there let's say we have a new variable user input and this is of type unknown it's not of type any which would be the default but unknown which is a different type introduced but hide script it might be unknown because we don't know yet what the user will eventually enter if it's a number if it's a string we don't know now the interesting thing about the unknown type is we can store any value in there without getting errors so this is all allowed if I now compile my file here you see I get no compilation error so thus far it's the same as if we wouldn't have assigned a type here and hence we have T any type or if we would have explicitly set any as a type but still unknown is different to any this here works but we'll run into issues if I have another variable let's say user name which should be a string and that's uninitialized here but then here i want to set username equal to user input now you see we're getting an error the type unknown is not assignable to type string so user name wants a string and of course unknown is not guaranteed to be a string here I assigned one but that's just the case in this line user input technically could hold any value because it's unknown now the interesting thing is if I switch unknown to any this error goes away because any is the most flexible type and typescript and it basically disables all type checking and type script just says I give up do whatever you want unknown is a bit more restrictive than any with unknown we have to first of all check the type that's currently stored in user input before we can assign it to for example a variable that one a string so since a string is wanted here we could check if type of user input is equal to string and typescript will detect this check and understand that in here what I store it username because it's inside of this if statement where I check for a user input being of type string user input is guaranteed to be a string and therefore I can safely assign it to username so I need such an extra type check here with unknown to be able to assign a unknown value to a value with a fixed type and therefore unknown is the better choice over any if you know I can't tell exactly what type I'll store in there it might be a number it might be a string but I know what I want to do with it eventually well just add an extra check to make sure that what you wanted you can be done so that if you want to work with a string you have a string and you're good and then unknown is better than any because it makes sure that you're not allowed to do everything but you have at least some type checking of course if you have a chance of knowing in advance that user input is always a string or always a string or a number well then you should use string or such a union type instead of unknown so unknown still is a type you shouldn't use all the time but it is better than any for the reasons described the last interesting type want to show in this module is to never type now we saw a function that returned white so that never returns anything never is another type functions can return and that might sound strange let's have a look at how it works let's say we have a function generate error here I expect to get a message which is a string and maybe some error code which might be a number now inside of this function let's say we throw an error so this should essentially be a utility function that generates error objects and froze them so here we might throw an object which we can do in JavaScript we can throw any object or any value as an error and that should have a message property in which I store the value of my message argument here and I want to have an error code property let's say where I store the code argument in so now this would be a valid function and we can call this with an error occurred for example and a code of 500 if we do that and we compile this file here we see that once this reloads we get our error well as an error here and this might sound pretty abstract but actually it isn't having utility functions like this would be pretty standard in bigger applications where you don't manually want to throw an error in ten different places of your app but where you want to reach out to one convenient function that builds the error object for you and maybe also froze it immediately so that you can call this function with different inputs but you always have an error being thrown now the interesting thing about this function is it does not just return white I actually can specify that it returns white because of course returns nothing but actually it does not just return nothing if we're totally honest this function returns never this function never produces a return value if I would try to restore the return value here and I console.log result and I'd n compiled my code and this execute we see there is no undefined being locked here because since an error is thrown this essentially crashes our script you could say it cancels our script and this will always be the case for this function of course we can wrap it and try catch so that we can still continue in the script but this function essentially never produces a value this function always crashes the script or this part of the script if you're using try catch and therefore never returns anything and hence the return type of this function actually is not just Wyatt but also never now the interesting thing is if you hover over it without assigning never you see the inferred type is white alls because never is a newer type it's been around for some time now but it wasn't built into the first versions of typescript and therefore why it is typically assumed and it's not horrible to leave it at that but you can be very clear and explicitly said never as the return type to make it really clear that this never returns anything so from a code quality perspective this might be clearer regarding your intentions and make it really clear to our developers reading your code that this function is intended to never return anything and to essentially crash or break your script or that part of the script and now our function that would never return by the way would be a function with an infinite loop so if we have while true in there that creates an infinite loop and that therefore all would be a function that never returns the error function here or the function Det generates and throws an error probably is the more common use case though so never also an interesting type which you can use on functions for cases like this one here now with that we had a thorough look at all the core types and types with basics you hopefully now understand how we create an assigned types how we assign types to variables and to parameters and why we do that how type assignments and types could differ from JavaScript type checks that JavaScript uses runtime types and typescript uses static types that matter during development that the built JavaScript code therefore does not include any type assignments it of course includes any type checks because that is regular JavaScript code but something like this here this is simply not allowed in JavaScript this is not supported syntax that's typescript only so that's hopefully clear and then we had a look at numbers strings boolean's at function types and setting return types argument types and also describing the type of an overall function which can be helpful if you want to have a variable that eventually holds a function we had a look at objects and arrays and enums and how that can be interesting and help you the same is true for Q 'pls and now we all had a look at aliases type aliases where you can merge complex types into Alice's which you can reuse we had a look at literal types and union types which can be useful for scenarios where you expect more than one possible type and now at the end we all had a look at unknown and never which are niche types but still in their niche they can be very useful and now with these basics we'll dive deeper into individual aspects and of course also explore other types and JavaScript constructs where typescript can be helpful in this module we'll take a closer look at the typescript compiler thus far we always just used it by running TOC and then pointing at a file which we want to compile now whilst that of course works it's not really feasible for bigger projects where you have multiple files or where you simply don't want to run this command after every change you want to see in practice in addition to that convenience which we currently don't have there also are a couple of interesting things you can configure regarding the compilation process which actually change what is compiled and how it is compiled and these are therefore the things we'll take a closer look at in this module now to get started I want to make sure that I don't have to rerun this command here this TOC command where a point at a file after every change I make because right now whenever I change something here in my typescript file and I wanna reflect that in my output file and on this web page here we have to save the file run the compilation again and then reload this file or if we have our npm start process running which we should have then at least our browser will automatically reload if we don't directly open the file but instead are on localhost 3000 but nonetheless even though winstead reloading automatically we still have to manually rerun the compilation command so to get rid of that we can enter watch mode that means we can tell typescript to watch a file and whenever that file changes typescript will recompile so for that we can still run the same command but now we add - - watch at the end or just single - W if we do that then we are in watch mode on that file and now whenever we change anything in there and we save that so that the file on the disk technically changes as well you see this automatically recompile and of course this all to me instead if we would do anything which is not allowed like for example reassigning to a constant and then a wrong type as well whenever we try to do that of course it also recompile but then just as if we manually run the command we see the compilation error down there so watch mode is already a big improvement the downside is that we still have to specifically target this file here and at the moment of course this is the only file we're working with but typically in bigger projects that's not necessarily the case so as I mentioned in the last lecture watch mode is a great start but what if we have more than one type script file what if we also have analytics dot TS file where we hypothetically send analytics data to our server now here to just have anything in there I'll just put in a console log statement but of course you could be sending HTTP requests to your analytics servers here as I said so let's say we also did import this file here in our index.html file if we point at analytics dot J's here which does not exist yet but which will exist after compilation then we could be loading these two files and of course we want to compile both files whenever one of them changes now for that it would be nice if we could enter some general watch mode where we just run tears see like this so without pointing at a file and it just watches our entire project folder and recompiles any types could file that might change well turns out that this is possible for that we just need to tell typescript dead this here is one project that should be managed with typescript and we do that by first of all and we all need to do this once running TSC - - in it so I'm not pointing at a specific file here I just run TS C and then - - in it here and again this is only required once it will initialize this project in which you run this command as a typescript project that means it will now basically tell typescript that everything in the folder where you run this command and therefore it's important that you navigate it into the right folder before you ran this command with the built-in terminal here in vs code I'm automatically in this project folder where my files are so that this project is now managed but that's good let's hit enter and what this does is it creates this Tia's conflict or JSON file this basically is the indicator for typescript at the project in which this file lies and all subfolders of this folder should be managed by the high school now if we look into this file we see there are a bunch of options most of them and commented out they're just there so that you see that you could set them and you got a short explanation here as well but we don't have to worry about those right now we'll dive into them in a second for the moment let's just close this file here and let's see what this gives us because what it does give us is that we can now run just TSC like this without pointing at a specific file and what this will do is it will tell typescript to go ahead and compile all typescript files so all dot TS files it can find in this project if I hit entry here you see this takes awhile and now what we got is this analytic start J's file and this app.js file now the analytics.js file was just created by typescript because it found that we have the analytics of tears file and as I said it will now compile all typescript files in the project and of course this can always be combined with watch mode you can run TS c - w or - - watch as i showed before and this will now enter watch mode for all typescript files so now whenever I change one of them and I save it it will recompile and it will recompile that file that changed and they are all to reflect the change in the javascript file and it's now here if I go back to my page we see sending data here as well because now the analytics TS file was also compiled so this is now how we can manage multiple files with typescript now one word about having multiple files when you work with multiple files as we're doing it here you can also import them into each other with modules which you might know from vanilla JavaScript there we have modules as well it is something I'll cover in a dedicated section of this course though so for now we just have two files which are not imported into each other but which are instead imported into index.html now with that out of the way though we know that we can manage this as a project and that we can compile multiple files here now let's have a look at the tears conflict on JSON file because this is a crucial file for managing this project it essentially tells typescript how it should compile these files now before we dive into the compiler options where we asked the name suggests can configure how the compiler behaves let's scroll down to the place before the closing curly brace but after this nested closing curly brace and let's see some of the options we can add here which don't affect the compiler or the compilation step behavior but instead how the compiler works with this project because there for example you can set a exclude option now if you add exclude here that will be an array and what you can enter here are paths to files which should not be included in compilation when you run TSC on the entire project so for example here we could say we want to exclude analytics TS from compilation and of course this does make much sense here but just to show how this works if we do that and we now rerun TSC and I first of all delete analytics.js so that we can see if it is recreated if we now are on tier C or TS c in watch mode you see no analytics.js file is created the reason for that is that we're excluding that file now of course for this file this does make a lot of sense because I typically want to include it but if you had a file that for some reason shouldn't be compiled you can exclude it like this you can also work with wildcards and for example if you had a it's named analytics dot def dot TS and you don't really want to compile that you could say all files that end with theft or TS should not be compiled and you can do that by also adding an asterisk here which is a wild-card basically and now types could will ignore any files that have dot theft or TS included you could also add asterisk asterisk slash here that would mean any file with that pattern in any folder will be ignored so these are things you can set up here the only thing I wanna set up here and that is a setting you will often find instead I want to exclude node modules and the idea here is that I don't want to compile any typescript files I might have inside of node modules now node modules is that folder that holds all the dependencies we install here in package Jason and the dependencies of these dependencies and therefore these are third-party libraries we're importing which we don't want to attach and if any of these libraries should ship some typescript code then we certainly don't want to compile it it will just slow down our compilation process and in the worst case it might even break our project so therefore it's quite common to exclude node modules here though I will say if you don't specify the X to 2 option at all node modules is automatically excluded as a default setting so you don't really need to add this option here this would be the default I just want to show that X through the exists and how you could use it if the only thing you want X to this node modules you don't have to add the exclude key at all if you do add it though you should set node modules because otherwise it will not exclude that now besides exclude we also have include and include allows you to do the opposite it allows you to specifically tell typescript which files you want to include in the compilation process and anything that's not listed here will not be compiled so if I point at apt es here you'll see if I rerun TSC we all will get no Analytics TS file or no analytics.js file I should say why because analytics.js is not included in include as I said if we do set the include key then we really have to include everything we want to compile so of course here we could then also add analytics TS here and with that addition we would start and compile it as you see now we have the analytics chairs file or as an alternative we specify a whole folder here which typically holds the files we want to compile exclude by the way if set alongs to include will filter down include so if we exclude some subfolder of a folder that is part of include then that excluded subfolder will be excluded so basically we compile include - exclude now of course here I don't want to set include I want to compile all typescript files and therefore I don't have to worry about that excluding node modules is all I need and as I explained theoretically I don't even need to add that because that would be excluded by default now you also have a files option this allows you to point at individual files so it's a bit like include with the difference that here you can't specify whole folders which you want to include instead that you really just specify the individual files you want to compile that might be option for smaller projects where you know you will only work with free files and for some reason you got a couple of our types good files which you don't want to touch though then you can set a list of files like this in reality you might not need that setting that often though and therefore that's it with the basic compilation or project management options here now of course there is way more we can specify though way more we can specify about the compiler itself and how it behaves during the compilation step so now that we have a understanding of how we can manage our files with the compiler let's dive into the compiler options because that's really interesting this allows us to control how our typescript code is compiled so not only which files but also how the files which are getting compiled are treated by typescript and there you see we have a bunch of options now you got short explanations next to these options some explanations arguably are a bit cryptic others are quite clear and I will say that a lot of these options most of these options will not matter in most project so you'll not set all of these options not even close you typically can ignore a lot of these options now I will pick up on the important options here throughout this course because some options only make sense when we learn about a certain feature and I want to dive into some options right now already though and for that let's go through that file from from top to bottom and see what we got there and let's start with the target option as you see this actually is set by default it's not commented out and what you do with this option is you tell typescript for which target JavaScript version you want to compile the code because what typescript does is it does not just compile new features like the type annotations that don't exist in JavaScript to JavaScript code so it does not just take care that this here works it also compiles the code to JavaScript that runs in in a certain set of browsers and you basically define which browsers support the compiled code by setting the target the default target here in this project as you see the initial target which is getting set up is es5 which means all typescript code is compiled down and we can actually see that if I run TSC here to compile all my files we see an apt es I'm using let and Const but an app J s we see var and that happens because we got a target of es 5 and in es5 world we don't have let and Const so the good thing here is that we can use typescript to generate code that works in older browsers as well but it still D up to us if we want to do that maybe we don't want to do that with typescript because maybe we got some other built tool that will then take care about the JavaScript translation and therefore we don't want to have typescript do that or maybe we want a ship code that only works in modern browsers because we know our app only will run in modern browsers and therefore alternative options can be seen here if you delete the value and then here in vias code at least if you hit control space to get the auto completion you see a bunch of suggestions and you see all available values here now over time this of course will change because we got new JavaScript versions released you saw we set this to e is 5 before if you don't specify target at all then right now typescript compiles to es free even so it supports an even older version but you can also go with es6 which is more modern which for example supports constant let or take even more recent version es6 is the equivalent to es 2015 just for the record so if we set this to es6 for example and I rerun DTS C command after changing that here's convict J's to file you will see that now an abscessed we got LED and Const because now that is supported there so that is up to you of course the more modern of a JavaScript version you pick here the more concise your generated code is because typescript has to compile less and less code or it has to work around non existing features in less situations and therefore the compiled code typically is then more concise and shorter so that's the target what about Diablo options we also got module here now module is an option I'll skip for now because it really makes sense once we learn about modules in typescript and how we can connect multiple files so let's ignore that for now Lib is an interesting window Lib is an option that allows you to specify which default objects and features typescript knows with that I mean things like working with the Dom let's say in index.html we have a button and on this button we say click me and when we click this button we just want to print a message now in apt yes we can select this button we can get access to this button with document query selector for example selecting the first button we find now if we do that then there's works we get no times good error here so if I go to my button and I add an event listener here I get an error here actually because typescript doesn't know for sure whether we find a button here for now we can work around that with an exclamation mark after this line and I'll come back to what exactly this does in a future it basically tells typescript don't worry such a button will exist we will get a value here so now we can add a click event here and then to find some anonymous function maybe we're a console.log clicked now the interesting thing here is not so much that I had to add the exclamation mark as I said I will come back to that but that if I run here see this just compiles now shouldn't types could complain that document is unknown to it how does it know that we have such a document constant or variable available how does it know that even if we have that available that it holds an object which has a curry selector method how does it know that button is something which has an event listener method how does typescript know all of that now you might say of course is nose because in vanilla JavaScript this would be valid code but keep in mind that when you write a typescript code you don't necessarily write it for the browser you could be riding your node.js application with typescript and err indeed this would all not work so the reason why this works is this lib option and as you see it's not even set here but if it isn't set then some defaults are assumed if it's not set the defaults depend on your JavaScript target here and for es6 it by default includes all the features that are globally available in es6 for example the map object which is available in year 6 therefore it wouldn't complain if you use map so it assumes all these years six features which are made available globally in JavaScript that they are available in typescript as well and in addition it assumes that all Dom api's are available you'll find the detailed descriptions about all these options by the way in the official Docs which are linked in lecture at the end of this module so long story short if the lip option is not set some defaults are assumed and these are typically the defaults you need to have typescript run in the browser so all the Dom API ends on if we comment this in and I now compile everything I dare forget an error because now by commenting it in we don't have to default settings anymore instead we now say hey please include some default libraries so some default type definitions you could say which I will give you in this array and as you see I'm not passing any description any paths any values here and therefore what I'm saying the typescript now is hey regarding all the defaults you know please take this into account and you know nothing so only if that's commented out it works because then times could we'll assume some defaults if I set the default explicitly well then types good of course adheres to what I'm setting here and hence here for example it doesn't know document it doesn't even know the console here so therefore we want to set this to more reasonable values and again if you hit control space in here you get all the completion and for example there we could add Dom that's an identifier and there are some predefined identifiers which types could understand again you find a complete list in the official docs the docs for this option are attached to this as well so this is identifier types could understand it's an identifier which basically unlocks all the Dom API is in typescript so the typescript understands what you're doing there so now already you see it knows console it knows document and so on so now since we're working with next-gen JavaScript we should also add two ears six option so that types could also understands all globally available es6 options and it's also a good idea to add Dom iterable and script host with that here we would unlock all the core JavaScript features you would want to work and this by the way is the exact default setup you get when you set target two years six anyways so if you comment this in and set it up like this you have exactly the same behavior as if you don't specify lib at all now here I will comment it in though and with that this will compile again setting this is a bit redundant though just want to explain what it does now although interesting is allowed Jas with allow Jas and by the way all the way of check chess you can also include JavaScript files in the compilation now with allow Jas a JavaScript file will be compiled by typescript so even if it doesn't end with dot TS types could will compile it with check j s it will not compile it but it will still check the syntax in there and report potential errors this could be nice if you don't really want to use typescript but you want to take advantage of some of its features and as far as typescript can help you with the any type only which is effectively what you have in JavaScript it will do so if you enable these options now we don't need it for this project and for this project we would want to make sure we don't double compile these javascript files which do stem from tactical files so we would have to tweak to include an ex to its settings a bit but you could use that in projects where you don't want to use typescript at all or where for whatever reason you have some vanilla JavaScript files next to your typescript files and you want to check the vanilla JavaScript files as well now let's fast forward a bit J's acts as an option that can help you with react Jas which does not really matter for us here declaration and Declaration map is also not important here DTS files are an advanced concept which matter to you if you're shipping your project as a library to other people and you need very basically a manifest file which describes all the types you have in your project that's such a DTS file source map is an interesting one though sourcemap helps us with debugging and development so to show what this does let me compile everything without that source map setting if we now go to the browser and we want to understand what our code does we can go to the sources tab here indie developer tools and there we find our JavaScript files now we can dive into these files and the good thing is these files are fairly readable to us humans of course because they contain JavaScript code in the end now that's good but what if we had more complex typescript code and we want to debug our typescript code and not the compiled JavaScript code in our of words it would be nice if we would see the typescript files here and not JavaScript files with the source map option you can get there if you set this to true and you run the TSC command again then you see we got these dot J's not map files being generated as well now if we look at them they're pretty strange files but what they do is they basically act as a bridge which is understood by modern browsers and the developer tools there to connect the JavaScript files to the input files so with these files generated if I reload here you see in the sources tab we now not just have our JavaScript files we also see our typescript files there and we can even place breakpoints in the typescript files and if I now click on that button for example it pauses in the typescript file which is of course super super convenient because that really takes our debugging process to the next level because we can work directly in our input files basically in our tax code files instead of the JavaScript files now nonetheless here I'll comment this out because we have a fairly simple project here and I don't want to have these extra dot map files lie around here but this is super useful in projects because it simplifies debugging let's move on we get the outfall option here now this option does not matter to us right now it won't work right now more interesting classes out der and route der the bigger your project gets the more you might want to organize your files typically you don't just want to have your files lie around here in your root level project folder instead what you often will see in projects is that you have a source folder and you have a dist folder next next so the dist folder has the job of holding all the output so all the JavaScript files let's say and the source folder might hold all our typescript files so we can move the typescript files into the source folder and if I now delete the JavaScript folder we have the problem that if we compile everything these type code files are compiled because typescript the compiler does look into subfolders but the output says next to our input files and that's something we can control with the outer for example if we set outer we can tell the typescript compiler where the created files should be stored we could set this to disk now if we do that then if you run TSC you will see that the JavaScript files indeed are not placed in the source folder but in the dist folder now we just have to adjust our index.html file and there point at dist apt Reyes and dist analytics.js or alternatively move the index.html file into the dist folder but then our dev server wouldn't work correctly anymore right now so let's just adjust these imports and with that we got a working application still as you see but now with a cleaner project structure now the good thing is if we had a subfolder here and analytics folder let's say and we had our type could file in there then if we recompile and it does not matter if you do it with this command or in the watch mode this folder structure you have in a source folder will also be replicated in the dist folder which is of course very convenient because that makes sure that you can import the files basically as you would import them in the source folder as well so that the structure you said there is Kent now you can also set the root directory and set this specifically at the folder where your files are stored in like in this example source to make sure that the typescript compiler does not look in our folders that's also something you could do with the include option down there right but with root directory the typescript compiler will not just look only at that source folder it also makes sure that project structure you set up there is kept in a dist folder now it did so by default before as you saw but keep in mind that before it would have included any typescript files here all the outside of source so for example if we comment this out temporarily if we had a user folder here on the top level with a user TS file where we have a user name of max let's say then if we compile this you will also see that user folder in the dist folder and now the source folder is included as well because now we have a type could file on a higher level and therefore the types of compiler things that our whole project again is the input and it replicates the folder structure it finds there in the distal der now that's of course not what we would want and that's where the routier option helps us now if we set this to source even if we had our folders with typescript files in there on the root level they would not be included in the output and the source folder itself would not suddenly end up there so off new set both routes der and outer to be really clear regarding where your input files live and where your output files should be generated in if we move on we can ignore composite we can have a look at remove comments should be pretty clear if you set this then any comments you might have in your typescript files will be removed in the compiled JavaScript files so if I comment this in and I compile my code you see an apt yes I have a comment in app J's it's not there so you can do that to make your files smaller and therefore this might be a nice option you can also set no Amit if you don't want to generate any JavaScript files now this might sound strange because that's the idea of typescript but if you just want to check whether your files are correct but you don't want to write all these output files to save some time for example in a bigger project then you could set this to true to just have the types of compiler check your files and report any potential errors without actually creating an output file import helpers is not really important to us here we can ignore that downlevel iteration is an advanced option it is interesting when you compile your code to older versions of JavaScript and you work with for loops then in some rare scenarios you could run into issues where the compilation doesn't work correctly this option if you turn it on gives you a more exact compilation which will work in these niche cases so therefore you might think you should always turn it on but it will also output more verbose code so you should only turn this on if you have loops and you see that your generated code suddenly behaves differently than it should regarding those loops we can't ignore isolated modules but there is one other option which is actually not even mentioned here which I still want to mention myself though and that steed no omit on error option you can set this to true or false and the default is false and what does this do if we set it to false let me show you where this might be a problem it is a problem if we introduce an error or it can be a problem let's say here I do have my button and I remove this exclamation mark now even though we don't fully understand what's going on the problem here simply is that typescript does not know that we certainly have a button here after all when querying for a button we might not get one if there is no element in the Dom sense satisfying this selector then this will return null and that's basically what types of complains about here we access something on a potential null object and that's not good now that's an error we have here if we compile our code we also get this error here in the console nonetheless the file is created so even if I delete the app J's file it will be recreated so even if we have an error typescript creates a JavaScript file this might or might not be wanted maybe you have an error in your tab good file and you don't really know how to work around it but you know it will not be a problem in the final app like here even if we don't know about the exclamation mark well if we don't know about the exclamation mark we might not know how to disable this error basically but still we know that this will work in our page here so we might be fine with compiling this despite having an error but of course in reality you should aim for error free projects and Rober learn how you can work around this issue then ignore it nonetheless you could set this to false or not set it at all because false is to default if you are fine with generating JavaScript files if you have an error if you set this to true however what will happen is that problematic files will not be generated if I now rerun this you see nothing is generated actually even the analytics TS file is not output there if we have some content in there besides console.log you see it's not getting generated and the reason for that is that we have an error in a file and if any file fails to compile no files will be emitted so here therefore we have to make sure we fix this error before we then can get typescript to again compile files for us and therefore it is an option I typically like to set because I'm not interested in getting JavaScript files if I still have errors in my type code files so that was an important first set of options now let's dive into these strict options because these are pretty interesting there is this strict true option and actually what this does is it enables all strict type checking options so effectively setting this is the same as if you would set all these options separately so you can either set all these options one by one or just set this option of course you want to set the individual options if you want to have some options set to false because otherwise they're all set to true if you want them all set to true then using just this option is of course way shorter now what do these options do though let's start with no implicit any no implicit any is a quite interesting option that helps us write better code let's go to our Analytics file here and there let's add a function send analytics that gets a data option let's say and there we could send this to a server but here I'm just console logging it then I call send analytics with the data so with the string now as you see my IDE already complains here and so does typescript the compiler because the two of course are connected if I try to compile this parameter data implicitly has on any type so this seems to be related to this no implicit any option indeed if I set this to false so if I set all strict options to true but I set this option to false which I can do then this error goes away both in the IDE and when we compile the code so what does this option do it ensures and I'll comment it out again to turn it on again because of strict truth it ensures that we have to be clear about our parameters about the the values we're working with in our code here we don't give types with any information about the type of data we'll get as a parameter here and we should if typescript is able to infer this then of course it's fine but here how what types could be able to infer it from this line well keep in mind that this function gets declared first before this file executes so at the point of time when the function is created there no chance of knowing what will end up in there so here we can fix this error by simply declaring the type and being clear about which type we use there now please note that if you had a variable locked and you set this to true here you don't get an error about this declaration even though it also gets a default type of any four variables this is okay for parameters it's not okay why is it okay for variables because what typescript asks for variables what is possible for variables what's not possible here because the function is created first here types which is able to track the values you assign you see okay I got locked here like this now I set it to true so therefore thereafter if I console.log locked here it's a boolean so typescript is here able to understand the flow of your code and they offer you don't need to be precise regarding the type here of course you want to be precise if you want to avoid that you can freely assign a new value which you can do here because it is of type any so you want to still assign a type to a white this but typescript is at least able to find out if the code you're calling works with the type it currently holds that's not the case here because there the function is to find before you call it and therefore typescript would have no chance of knowing if what you pass in there can be used inside of the function strict null checks is another important option it's actually related to our button selection which we have here remember I had to add this extubation mark here to make it work otherwise I'd get an error now we can also get rid of that error without adding the exclamation mark by setting strict null checks to false so let's do that here and let's save this and as you see this error is now gone here and I can't compile all files and what do is strict null checks you they tell typescript to be pretty well strict regarding how you access and work with values that might potentially hold a null value and button here might be now it's not always pointing at a button element it's not always pointing at such an element because even though you have such a selector here a button might simply not exist on the page on which this script runs and therefore typescript can't tell because it's not diving into your HTML file and looking at that it can't tell whoever it is will be successful or not and if this fails to return a pointer at a Dom node then it will return null or undefined to be precise but that's treated equally here so therefore then button might hold a null value and therefore this code could fail indeed if I comment out this button here if I now compile everything it works because I disabled the null checks but idea for now I have a runtime error because I can't call event listener an event listener on null and I got null here because I got no button now this is a mistake we could avoid by setting strict null checks to true and that's automatically set if we have strict set to true where typescript anticipates that this might happen and therefore forces us to work around that now one cheap workaround is this exclamation mark operator here this tells time script that you the developer know that this button exists or that this operation will yield a non null value now maybe you do you certainly do you know that you are working on the HTML code and that there is a button here that this selector here will work so it would be fine to use the exclamation mark in this scenario if you have another scenario where you don't know for sure if it works and you just hope that it works then it might be better to simply wrap the code that might fail in an IFFT check which will be there at runtime as well of course you could simply check if button is truthy which it won't be if it's null or undefined and move that code into this if check here now even without the exclamation mark in strict null checks mode we get no error because typescript understands that this code is inside of this if statement and that this if statement make sure that button is not null and that this will not fail so this might actually be the cleaner workaround however of course to save code if you know with certainty that something does exist using the exclamation mark is shorter and an absolutely fine option here I said both so that we see both of course you just need one of the two things eerily if check or the exclamation mark strict function types here is a little bit of a more advanced setting catching some some nice box which you might not have in many applications it is related to well function types you might be setting up so not types inside of functions but if you define how a function should look like regarding its parameters and return value and you create such a function type which you learn about in the basics module then there you can introduce box if you work with classes and inheritance which we have learned about yet which we haven't used yet and therefore for now let's ignore this strict bind call apply that can be helpful if you do work with bind call or applied for that let's quickly see an example here we have our our button and our function there now let's say this would be a function which we define here with the function keyword or as an error function doesn't matter I'll use the function keyword here click handler and in there I console.log clicked and now here we point at clickhandler and for some reason we want to make sure that when is execute we pass in certain arguments or we set the this keyword in there to a certain value now let's say here we do you expect a message argument which should be a string and we wanna output this here as well now since clickhandler is passed to add eventlistener like that so that the browser basically executes this for us if you want to pre configure the arguments which will be passed in we can use bind and bind as our first argument takes what we want to bind the this keyword to and here we could say it does not matter to us because we're not using this in this function so we bind it to null now you see here i get an error i get an error that can be avoided if i set strict bind call and apply to false now you see the error is gone now what does this option do therefore it basically checks on which function you're calling bind call or apply and it checks if what you are setting up here makes sense and here typescript sees we want argument we want a parameter in click handler with bind we're not configuring that though and therefore here we get an error if I set this back to true or I just commented it out because of course it is set to true by default by setting strict to Dru we did forget the error again now if we wouldn't expect an argument here you see the error would be gone down there if we all remove the message because typescript understands our code and sees you're not passing in any arguments to that method or to this function because it doesn't take any so that's fine but of course here we want one so we get an error the solutionist who provide this second argument here which is the first argument we want to pass in now typescript is really smart here and for example if you pass in a number it would still complain because it understands that I need a string here if I pass in a correct string though like you're welcome then it does not complain anymore because now it understands this and it sees that this is matching my function definition here so this is a very useful behavior that makes sure that you don't accidentally use fine call or apply in a way that does not work with your code now a strict property initialization becomes important once we work with classes we can ignore it for now no implicit this also does not matter right now it has to do with the this keyword and typescript basically tries to warn you if you use to this keyword in a place where it's not clear what it refers to and always strict simply controls that the JavaScript files which are generated are using strict mode so that this is added with that we covered all these strict options now if we move on we get more options no unused locals no unused parameters no implicit returns this helps you with code quality basically typescript will complain if you have certain unused variables and so on so if we turn these free options on for example this option helps you have switched statements where you might forget the break keyword but if we turn these free options on what typescript will complain about is for example if you had a username variable here locally in this function and you don't use it you see this has yellow squiggly lines because it's not an error really it's more like a warning or a hint so if I compile here you see now however I do get an error because typescript only knows errors and there we see that user name is declared but its value is never read because we made sure that we don't want unused local variables unused global variables so if I had something like app ID here are allowed though because typescript can't know if you maybe need that globally defined value in an average crypt file so therefore this is allowed but in a function where there is no other place where you could need it typescript will complain now if you have unused code and that's generally a good idea allows you to strip out such unused code same goes for unused parameters if you would take a age here for one of course bind is broken now but even if we pass this in this works but now again typescript and therefore all to the IDE tells us that this is unused and indeed it is so maybe you should remove it or start using it so that's no unused parameters and no implicit returns means that we'll get an error if we have a function that sometimes returns something and sometimes it does not let's say we have an ever function add where we get two numbers number and and who is a number and of course we can return + 1 + + 2 but Saver for some reason checking if n1 plus n2 is greater than zero because we only want to return if we have a result greater than zero and then we want to return the value otherwise we want to return nothing we don't want to return well then we get a warning because of that extra setting with no implicit returns typescript detects that not all branches in this function lead to a return statement and because of our setting that's not allowed we at least have to deliberately not return anything here by adding the return keyword just omitting it is not allowed here it is allowed if you have a function that does not return anything in no branch but if you have at least one case where your function does return something then you have to make sure you return something in all cases and with dead were nearing the end of this colloquy can ignore the module resolution here all these options actually are pretty advanced that don't matter to us here don't matter to you in a lot of projects source map options allow you to tweak these source Maps we had a look at earlier so these translation files from JavaScript to typescript typically default settings should be fine here so if you don't know what you're changing and why you're doing it you typically don't need to change anything here and regarding these experimental options I'll have a look at them specifically at experimental decorators later in the decorators module this basically enabled certain features to be used in typescript which are really experimental where it's not sure if they will end up in JavaScript at some time in the future and where you still might want to work with them then you explicitly have to tell typescript that you want to work with these features and you can do that with that configuration but again I will come back to that and therefore now we walk through this file a lot of options you can set there and as typescript grows you typically also get more and more options added here therefore the official Doc's are of course always a great place to dive deeper and to make sure that you don't miss an interesting option that might help you in your project so now that we have a properly configured project let's dive a bit deeper into how you can debug your project or how you can have a great development flow I show you my basic idea is set up at the beginning of this course really make sure you got the right extensions installed there forward type script it comes down to es lint which can help you with linting your typescript code so with improving the code quality though you might need additional configuration for is lint to have an effect it can help you in more advanced projects so but more interesting than that you wanna really use prettier to automatically format your code and have a nicely formatted code and you might want to give debugger for Chrome a try because that allows you to debug your typescript files even from inside Lia's code through chrome but without using the chrome dev tools of course you can use those as well as you learned if you do enable source Maps here but you can of course always do you get these translated files there as well which is really nice but you can also use vias code you can place breakpoints here let's say in a click Handler and now to launch your files here through Mia's code you need to enable source maps as well but we still will be able to use Tia's code instead of the browser dev tools so enable source Maps place your breakpoint and then go to debug start debugging now the first time you run this it should ask you for an environment and there with that debugger for Chrome extension installed you should be able to choose chrome it will now go to a launch JSON file where you configure how it should launch that and there you should point it at localhost 3000 because that's where our development server is running and of course that process so the npm start process should be up and running so point at localhost 3000 here and as a web root we you can leave that placeholder here which means this project folder is assumed to be the host of your files which is the case and now compile your code so that the source maps also are generated after setting the source maps conflict to true so then do we now have T's in the JavaScript code then with your breakpoint added here and your launch chasing configured let's run debugging here start debugging now for real and it will open up a new tab now automatically this tab will be closed whenever you quit the debugging process or if you close the tab the debugging process will quit so now with dead you entered this debugging view here in vias code where you can track variables watch certain expressions and see the current call stack if you now click on click me you should be taken back into the editor and code execution pauses at your breakpoint in the typescript file and now you can walk through the file here inspect local values for this keyword or for the message variable for example script wide variables you might have and global variables you got access to global objects you can watch certain expressions like message plus multiple exclamation marks and well then you can always track the value which is in there here in this window if you wanted to use that that would work and you can see the current function call stack for example that we're currently in a click Handler and now you can step through your code with these controls to step to the next step skipping over the next function call stepping into the function call or stepping out of the current function call and the call stack of course here will adjust according to that and with that you can ignore this browsersync thing here with that you can always resume code execution by clicking the play button and only pause whenever you reach your breakpoint the next time so this is how you can debug code you can remove a breakpoint by clicking on it this is how you can debug code from inside vs code with the help of the built-in debugging tools the chrome debugger extension the right configuration and source maps which are set up in your typescript config and that's it for this module we had a very detailed look at the typescript compiler how you can consider it and how you can make sure that it really compiles your code the way you want we had a look at all these different options especially the strict options really allow you to write correct code and not run into strange bugs strange runtime bugs you might face for example with the strict null checks and in addition to that we had a look at debugging how you can easily configure drom and vias code such that you can debug from inside various code debugging from inside chrome with source maps and the sources tab of course is always an option the key here also are the source maps which you are configuring to be generated in the TS config file which are these map files that live next to your JavaScript files they basically act as bridges for the debugger between your JavaScript files and your typescript files and with that we know a bit more regarding how to manage our projects let's now see what else we can do with typescript and JavaScript [Music] you [Music]
Info
Channel: Academind
Views: 982,062
Rating: 4.9461989 out of 5
Keywords: typescript, learn typescript, typescript 2020, typescript course, typescript for beginners, learn javascript, typescript full tutorial, typescript free tutorial, typescript udemy, typescript vs javascript, typescript getting started, maximilian schwarzmĂĽller, maximilian schwarzmueller
Id: BwuLxPH8IDs
Channel Id: undefined
Length: 196min 40sec (11800 seconds)
Published: Tue Jan 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.