Learn TypeScript in 50 Minutes - Tutorial for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys my name is vishwas and today we are going to master the basics of typescript we will begin by understanding what is typescript and why we should learn it we will then set up our development environment after that we are going to dive into the concepts of typescript we have variable declarations variable types functions interfaces classes and access modifiers by the end of this video you will have mastered the basic concepts of typescript all right then let's begin first up what is typescript typescript is an open source programming language developed and maintained by Microsoft it is a typed superset of JavaScript that compiled to plain JavaScript which is understood by the browser's in simple terms combine the JavaScript we know with es6 year-seven and a few additional features and end product is typescript now why would you want to use typescript as opposed to other languages like dart or CoffeeScript or even plain old JavaScript the first one is its relation to JavaScript typescript is superior to its counterparts like CoffeeScript and dart in a way that typescript is just extended JavaScript dart and CoffeeScript are new languages in themselves while typescript is not you can even rename a dot J's extension file to dot TS and it would work perfectly fine the second reason is optional static typing and type inference javascript is dynamically typed which means javascript does not know what type a variable is until it is actually instantiated at runtime which is too late typescript on the other hand add type support to JavaScript as a result I've identified as and when you type your code and during the compilation step this results in less error-prone code and avoiding having to wake up in the night at 2:00 a.m. to fix a production issue and the best part is specifying the type is completely optional when you don't specify a type typescript will infer the type for you and still point out the errors which would otherwise be seen only during runtime another important reason to consider typescript is the enhanced IDE support with typescript we get intelligent support ability to refactor code easily and the red squiggly line whenever there is an error along with the description of that ever this helps you spend more time on coding and less time debugging over the past year typescript has seen rapid growth and usage in a wide variety of applications typescript is the main programming language of angular it has found its way into react and view as well Microsoft is actively working on the project and features are being improved constantly very soon you're going to be hearing a lot of typescript in the world of web considering all these reasons I would say if you haven't already now is a great time to learn typescript now before we get started with the concepts we need to set up our development environment the first step is to download and install node.js so go to node.js dot-org download and install the latest stable release in the command prompt when you run the command note - V you should see the version installed on your machine second step is to install typescript again in the command prompt run the command npm install - g typescript this will install typescript globally once the command completes run the command TSC - v to know the version installed on your machine you can see that I have three dot o dot one finally we need an editor to write code I will be using Visual Studio code and you can download it from code Visual Studio calm alright with that we have everything we need to get started with learning typescript let's begin with a simple hello world program so open visual studio code and you can see that I have already created a folder called typescript this folder will contain all the files for this particular tutorial let's create our very first typescript file so new file and I'm going to call it main dot T s so ts is the extension for typescript now within the file I'm going to declare a new variable let message is equal to hello world then let's lock this to the console console dot log message and that's it the next step is to compile this down to plain JavaScript using the typescript compiler so open the integrated terminal that is control backtick and run the command TSC followed by the filename which is main dot TS now if you wish to you can leave out the extension that is dot TS you can simply run the command TS c main the command creates a file main dot j s which contains the transpiled code we can see that the let declaration has changed to a VAR declaration so the compilation step is successful now to run the code we don't really need the browser we can make use of node so in the terminal run the command node main dot j s again the extension is optional but this is the first time and I want you to know we are running the JavaScript file and not the types Ted file so when I run the command node Minges you should see the output hello world so that is a very first typescript program now you might have noticed we have an error and if I hover on that you can see that it says cannot read Eclair block scoped variable message this happens because the file is treated as a script rather than a module a module has its own scope whereas scripts share the global scope to get rid of this error we need to add an export statement at the top which exports nothing by adding an import or export statement typescript treats this file as a module instead of a script so at the top at the statement export and then nothing just a pair of curly braces let's recompile this so TFC main TS you can see that the error disappeared and the change is reflected in the JS file as well now a useful addition to our workflow here would be to automatically recompile that typescript file whenever there is a change we can do that using the watch option of the typescript compiler so in the terminal run the command T as C main - - watch you can see that the compiler is now watching the file for changes so if I go back to main dot es and change hello world - let's say welcome back save the file and you can see that the compiler created the J's file with the new code welcome back I can open another terminal and run note main and you can see the output welcome back so this is the overview of how typescript works you have a type script file which gets transpired to a JavaScript file which is then used in your application alright with that understanding let's now focus on the various concepts that typescript brings to the table first up variable declarations unlike traditional JavaScript typescript encourages the use of left and Const keyword for variable declarations if you have played around with JavaScript for a while you probably know how scope and var declarations can trick you javascript has only global scope and function scope there is no block level scope this is something that often misleads programmers used to other languages to make things worse it is also not an error to read eclair the same variable multiple times let and constellations solve these problems both let and Const support block level scoping and you can't read éclair variable multiple times with left or Const for example let X is equal to 10 Const Y is equal to 20 now if I try to read Eclair X by saying let X is equal to 30 we see there is an error cannot read Eclair variable X and the question is what is the difference between the two and when to use one over the other the difference is that let declarations can be done without initialization whereas Const declarations are always nish alized with a value and cons declarations once assigned can never be reassigned so we can have a declaration let some but we cannot have Const title we get an error constellations must be initialized so when to choose one over the other if you feel that a variable must never be reassigned a value go with Const declarations if not go with let declarations for example the sum of two numbers can change often but the title of your application may never change so let declaration for some and Const for title by making use of left and cons keywords for variable declarations typescript is already helping reduce the amount of both in our code right so that is about variable declarations in typescript next let's move on to variable types which i think is the essence of typescript first up let's take a look at the basic types in typescript that is boolean number and string now we have already seen how to declare and initialize a variable so let is beginner equal to true but how do we assign a type to this variable the syntax is right after the variable name append a colon followed by the data type so : and then boolean so we now have a variable is beginner of type boolean which is initialized with a value of true similarly we can declare a number let total of type number if you want this to be initialized that total of type number is equal to 0 and then of course we have the string type so let name of type string this is going to be equal to which was pretty straightforward but in typescript you can also use template strings and template strings can span multiple lines and have embedded expressions for example let sentence of type string is equal to in backticks which is the key just below your escape key I'm going to have my name is then we can embed the variable value with dollar and curly braces and the variable is name and in the next line I am a beginner in typescript now we can lock this sentence to the console so console dot log sentence in the terminal run the command note main and you should see the output my name is vishwas I am a beginner in typescript so multiple lines with embedded expressions so boolean number and string are the basic types but what really is the use of having types there are two important ones the first one is static type checking you can see that when I try to assign a boolean value to the name variable name is equal to true we get the red squiggly right away type true is not assignable to type a string and in the terminal you can see the error from the compiler as well found one error and that is at line name is equal to true line 14 unlike plain JavaScript typescript helps you with static type checking which can prevent you from making mistakes that would otherwise go unnoticed during development the second important use of having types is intelligence for example if I type name dot you can see the intellisense providing the properties and methods applicable to a string type and when I type total dot you can see the suggestions are only related to a numeric type again intellisense is what the most valuable things during development static type checking and accurate intelligence both are only possible because of types we have assigned to the variables alright let's continue with variable types we have two more types null and undefined so you can actually declare a variable that is of type null or undefined in typescript let em of type null is equal to null and let you of type undefined is equal to undefined but there are not much use on their own that is why in typescript null and undefined are classified as subtypes of all other types that means to say you can assign a value of null or undefined to either boolean number or a string typed variable so we can have let is new of type boolean is equal to null and also let my name of type string is equal to undefined that works perfectly fine as well building on these basic types and the subtypes we can declare an array of values using the array type there are two syntaxes for declaring an array type the first one let list 1 : of type number and then square brackets is equal to an array of numbers 1 comma 2 comma 3 or we can have the other syntax let list too if an array of type number and this is equal to 1 comma 2 comma 3 there is no advantage in one syntax over the other it is completely up to you to pick the one you like now having an array of values of the same type is great but sometimes you might have an array that contains values of mixed type for that purpose typescript provides the tuple type for example we can create a pupil that contains a string and a number so I can have let person 1 it is going to contain string and a number and the array contains a string and a number the thing with a tuple though is that the number of elements in the array are fixed so the person one tuple indicates that the array contains exactly one string value and one numeric value and the order of the values has to match the order of the types so I cannot simply add another numeric value so 22 comma 35 it throws an error at the same time I cannot swap the values and expect it to work as well I cannot have 22 comma Chris so fixed number of values with different types tuples are the way to go next up we have the enum type which is a way of giving more friendly names to a set of numeric values for declaring an enum we use the enum keyword and that is followed by a name for the enum which is in turn followed by the values in a pair of curly braces for example we can have an enum of colors so enum color within curly braces red green and blue now I can declare a variable of type enum and assign a value so let see of type color and this is going to be equal to color dot green let's also log the values so console dot log C now in the terminal when I run node main you can see that the value of C is 1 in values begin with a value of 0 so red is 0 green is 1 and blue is 2 if you want the number starting at a different value specify that in the enum declaration so let red is equal to 5 now when I run node main you can see that green is at a value of 6 so red is 5 green s 6 and blue is 7 a lot of the times you may store a value as a number in the database we might have a color field and the person who created the table might know zero is for red one for green and two for blue but in code that is not a good practice it would be really difficult for someone working on the code later on to understand what is going on with the random number assignment instead we create enums and assign an enum value which is more code friendly the next type I want to talk about is the any type now if you're unsure as to what a variable type would be make use of the any type if you're expecting a value from a third-party library or user input that the value is dynamic make use of the any type and that will allow you to reassign different types of values for example let's have let random value of type any is equal to 10 now I can assign random value is equal to true and random value is equal to which was-- you can see that the compiler doesn't throw an error this is particularly helpful when you are just migrating from JavaScript to typescript the any type is also the most capable type in typescript it encompasses values of every possible type and it doesn't force us to do any checking before we try to call construct or access properties on these values for example let my variable of type any is equal to 10 with my variable a number of errors can occur so I can type console dot log my variable dot name I can even call my variable as a function or I can call a method that is applicable only to a string type my variable dot to uppercase you can see that typescript does not throw an error in any of the statements because my variable is off type any to tackle this issue type step 3.0 introduced a new type called unknown unknown type is very similar to the any type so any value is assignable to type unknown however you can't access any properties off of an unknown type nor can you call or construct them if I change my variable to type unknown from type any you can see that we get the errors right away to be able to get rid of the errors we need to use a type assertion to convince the type system that we know better so we have to change my variable as string so now type script assumes that we have made the necessary check type assertion is similar to typecasting in other languages we are saying that my variable should be treated as a string and then the to uppercase method can be applied and it is also possible to have user defined type guard I'm going to create a new function that checks if an object has a name property or not so right before the console log I'm going to have the function the function I'm going to call it has name it is going to have a parameter object of type any and it is going to return an object which contains the name property as a string and within the function we are going to have return object and type of object is equal to object and name property exists in the object so we are basically making a check to see if the name property exists in the object or not now I can change the console log - if has name my variable console.log my variable dot name and you can see that we don't have an error anymore the function called of course is an error so let's just remove that so that is about the unknown type alright with that we wind up on the major types in typescript now let's take a look at two concepts that revolve around types in typescript let's begin with type inference if you recollect I did mention earlier that specifying types is completely optional so I can declare a variable let a and then assign a is equal to 10 and I can also assign a is equal to true and that works perfectly fine just like clean JavaScript but in some scenarios typescript as always wants to help us out so let me declare another variable let B but this time let me also initialize the variable in the declaration so let B is equal to 20 now when I try to assign another value V is equal to true you can see that we get a type error when I hover on the error it says type true is not assignable to type number but hang on we did not specify a type to variable B what happened here is that typescript inferred that type of variable B if I hover on B you can see that it says it is of type number and when I type B dot you can see the intellisense providing methods that are only applicable to in number type so type inference again provides static type checking and intellisense support you might think if typescript infers the type for us why specify it at all in the first place well type inference takes place when initializing variables and not all the time as we see in the right now type inference does not work on variable a where there is no initialization types are also necessary in other situations which we will cover shortly all right the next cool thing with typescript is the ability to specify union of types for the same variable for example I can declare a variable multi type to be of type number and boolean using the pipe character now I can assign a number so multi type is equal to 20 or I can assign a boolean value so multi type is equal to true both of them work without any errors again a use case for specifying multiple types would be when a value is not under your control it could come from a library from an API which might send a numeric value as a string value or from user inputs now if that's the case why would you want to use a union of types instead of just any type right I could just as easily write let any type of type any then any type is equal to 20 and any type is equal to true well there are two reasons first reason the Union types restrict to the specified types whereas the any type has no restrictions I could assign a string value to the any type variable but not to multi type variable it would throw an error the second reason is intellisense support for example after assigning a value of 20 when I try for intellisense you can see that we get a list of methods supported on the number type but the same when I try on the any type there is no intellisense support as you can see union type is a pretty good feature in typescript so type inference and union types were the two concepts I wanted to discuss all right that is about variable types in typescript all right now it's time for functions in typescript let's see how the concept of types lends itself to functions when writing code and go back to vs code and let's create a simple function you function add takes two parameters num1 and num2 and returns num1 plus num2 this is how you would see a function in JavaScript in typescript dope we can specify types for function parameters so we can have number one of type number and num2 of type number as well now i can call the function passing in five and ten and that is going to be okay so add five comma 10 and that works perfectly fine but when I try to pass in non-numeric type you can see that it throws an error so add five comma a string value of 10 you can see the red squiggly argument of type string 10 is not assignable the parameter of type number so number is doing the trick here we have static type checking for parameters and we also get intellisense support when I type add and open the parentheses you can see the intellisense accepts two parameters of type number and if you also notice in tel sense also tells you the return type of the function which is number if this was inferred by the compiler you can also explicitly specify in the function definition so right after the parameters : and then the return type which is of course number that is about using types with functions apart from types type script also has other great features when it comes to functions and I want to discuss two of them optional parameters and default parameters in typescript every parameter is assumed to be required by the function if you call the function without a parameter it throws an error but in plain JavaScript it would have been possible to call the add function without any parameters the parameter with the receive a value of undefined we can get this functionality in typescript by adding a question mark to the end of parameters we want to be optional for example if I want num to parameter to be optional I simply add a question mark at the end of the parameter name now I can call the function with just one parameter add five the second parameter is treated as undefined so we can change the function definition to handle the undefined value as well if num2 is a true T value return num1 plus num2 else just return number one the second call is just going to return five also make a note that you can have any number of optional parameters but the condition is that optional parameters must always be after the required parameters so if I wanted num1 to be optional and num2 to be required I would have to interchange the order of the parameters num2 would have to be the first parameter followed by num1 which is the optional parameter on the lines of optional parameters we also have default parameters in typescript default parameters are basically like optional parameters with a set value instead of undefined let's take a look at an example let me remove the question mark and instead we assign a value to the parameter num2 of type number is equal to 10 now the first function called returns 15 as expected for the second function call it is that there is only one argument and that value is passed to num1 as num2 is not passed in it takes the default value of 10 and still returns 5 plus 10 15 so default parameters are like optional parameters with a set value instead of undefined all right with that we conclude with functions in typescript next let's take a look at interfaces now what I haven't told you so far is that it is possible to specify an object as a type in typescript for example let's create a new function function full name of this has a parameter person which is of type object the object has two properties first name of type string and last name of type string as well within the body we simply log to the console first in dot first name space person dot last name I'm going to create a new object which resembles a person let P is equal to an object has a first name of value Bruce and last name of value Wayne and I can now pass this object when calling the function so full name passing in the person P when I run the code note main you can see Bruce Wayne printed out in the console so everything works as expected and that is fine but right now the person parameter has just two properties so it is not really a problem to define the function but imagine an object that has five to ten different properties for example an address object which contains line 1 to line 3 city state country postal code telephone and so on and if that doesn't make it worse imagine having so many functions that use the same address object as its parameter the code will start to look clumsy and code maintenance will be difficult as a solution to that we have interfaces in typescript we can create an interface of the person object and use that interface as a type for the function parameter so interface person it's an object that has first name of type string and last name of type string as well in the function parameter will now be of type person so I can remove this object and have the interface person you can see that the code looks way more cleaner now the same interface can easily be used as a type in multiple functions and any changes to the person type happens at one place definitely easier to maintain the code it is also possible to specify that a property of the interface is optional add a question mark to the end of last name and it is now an optional property of the person type I can remove the property from object P and you can see that we don't have any errors suppose last name wasn't optional you can see that it throws an error now a very straightforward use case for optional properties is forms for example a registration form there can be a specific type of data that the registration form is supposed to gather for which you can use an interface but not all form fields are mandatory optional properties can be used in such situations alright so that is about interfaces in typescript let's wind up this beginner tutorial - typescript by learning about classes and access modifiers in clean JavaScript there is no concept of classes and inheritance was through prototypal inheritance which is kind of a strange concept to get used to if you are from an object-oriented background to overcome this just like es6 typescript also supports classes to build applications using the object-oriented class-based approach let's understand with examples first let's see how to create a class so class employee you employee meme of type string you a constructor to initialize the employee name you and a Greek method that simply locks to the console good morning employee name and the syntax should look familiar if you've used c-sharp or Java before to declare a class named employee the class has three members a property called employee name a constructor and a method grid after defining the class it is now possible to create an instance of this employee class so let employee one if equal to new employee and we can pass in a name for the employee let's call it vishwas the next line we can log the name and then call the greet method of this particular employee so console dot log employee one dot employee name and then employee one dot greed when we run the code we should see the output which was followed by good morning vishwas so that's the basic idea behind classes nothing different from C sharp or Java but totally different to what plain JavaScript was capable of and because of classes it is now possible to have class-based inheritance let's create a new class called manager a manager is just an employee with some extra privileges so instead of repeating the properties of an employee in the manager class we can simply inherit them and for inheritance we used the extends keyword so class manager extends employee of this derived class also has a constructor the constructor needs to accept a name parameter that can be used to initialize the base employee class constructor and we do that using the super keyword so the parameter let's call it manager name which is of type string and then we use the super cleaver to call the base class constructor so we passing the manager name which gets initialized to the employee name in employee class so basically when you instantiate a new manager the manager class constructor called the employee class constructor to initialize the employee name property let's also add a method to the manager class I'm going to call this delegate work and we simply log to the console manager delegating tasks now I can create a new object of the manager class that m1 is equal to new manager we pass in a name so this is going to be Bruce now with this manager instance in addition to the delegate work method you can see that we have access to the employee class properties and methods as well so m1 dot delegate work m1 dot greet and console log m1 dot employee name when I run the code you can see that we have manager delegating tasks good morning Bruce and then the name Bruce that is how inheritance works in typescript all right for the final topic about classes let's talk about access modifiers access modifiers are basically keywords that set the accessibility of properties and methods in a class let's go over public private and protected access modifiers by default each class member is public so we can freely access them throughout the program you can see that we have accessed employee name in line 103 and line 1 1 8 you can of course explicitly specify employee name as public using the public key word so public employee name of type string the next modifier is private if you declare a class member as private it cannot be accessed from outside of its containing class so if I change public to private you can see that we straight away get the errors properly employee is private and only accessible within class employee so it can be accessed within the grid method which is inside the employee class but again not outside the employee class this is a way to secure the class properties another point to note is that you cannot access a private member even in the derived class so in the delegate work method I cannot have this dot employee name you can see that it throws an error now sometimes you want a derived class to have access to the base class properties but the property should not be accessible outside the classes in such scenarios we use the protected access modifiers you can see that if I change private to protected within the derived class we don't have an error so I can access this dot employee name but outside of the base class and the derived class we get an earth so employee one dot employee name and m1 dot employee name so these throw an error so public for free accessibility private for accessibility only within the class and protected for accessibility within a class and the classes derived from it that is about access modifiers and classes in typescript alright with that we are done learning few of the important concepts in typescript you should now be in a position to dive into some of the other advanced concepts that typescript offers well I hope you guys enjoyed the video thank you guys for watching don't forget to subscribe I'll see you guys in the next one
Info
Channel: Codevolution
Views: 626,260
Rating: 4.9211664 out of 5
Keywords: Typescript, TypeScript, Typescript Tutorial, TypeScript Tutorial, Typescript Tutorial for Beginners, TypeScript tutorial for Beginners, Learn Typescript, Learn Typescript in 50 minutes, Codevolution
Id: WBPrJSw7yQA
Channel Id: undefined
Length: 48min 10sec (2890 seconds)
Published: Mon Aug 06 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.