#53 Type Guards in TypeScript | Advanced Types in TypeScript | A Complete TypeScript Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this lecture we are going to learn and understand what are type guts in typescript in typescript type guards are a powerful mechanism that allows you to refine the type of a variable based on runtime checks and this enhances code reliability and maintainability by providing more precise type information to the compiler now what actually is a typ card type card are expressions that typically return a Boolean value or the variable itself cast to a more specific type they are used within conditional blocks like if statement or function return types to narrow down the type of variable after a type check and this enables you to safely access Properties or methods that might only exist on certain subtypes let's try to understand common typu techniques let's go to vs code and to understand type guards let me first go go ahead and let me create a type for that I'm going to use this type keyword and I'm going to create a custom type called string or number and this string or number type it can allow us to store a string value or a number value in a variable so here I'm going to use the union type string Union number so for any variable when we specify the type as string or number that variable can only store a value of either string type or number type now I'm going to create a function and I'm going to call this function as addition and this function it is going to take two parameters it is going to take a parameter a and I'm going to specify the type here as string or number and it is going to take another parameter B and for this also I'm going to specify the type as string or number okay now when we are going to call this addition function there I can pass string values like hello comma world or I can also pass values of number type for example 20 comma 30 or I can also pass a value of string type and number type something like this so all these three will work right and for each of these cases we will have different results for example when we are passing two strings in that case this addition it should concatenate these two strings right when we are passing two numeric values 20 and 30 in that case it should add those two numbers and when we are passing a string value and a number value in that case again it should concatenate this string value and this number value by converting it to a string so we can simply say return a + b but when I do this here you will see that it is giving us an error that operator plus cannot be applied to types string or number because this plus can be applied on string type or on number type but the string or number it is a custom type right so here what we are going to do is we are going to do the type check and based on the type check we are going to return results for example we will check if type of so for that we are using this type of operator dat we have already talked about it so if type of a is equal to equal to string or if type of D is equal to equal to string so if any one of these parameter is a string what we are going to do is we are going to concatenate them so for that we will say a do2 string so we are converting that a to string type plus b do2 string and then we are going to return the result okay so here first we are doing the type check because this A and B it is of type string or number and that's why we cannot directly use this plus operator on string or number we can use it on only string type or only number type so we are checking if a is of type string or B is of type string in that case we will do the concatenation the string concatenation otherwise if a and b are not of string type in that case we are going to add them and now you see we don't have any error so this function here it is either going to return a string value or it is going to return a number value so if I go over this addition you will see that the return type of this addition is string or number okay so here we are doing the type guarding so using type of operator we can do type guarding this is one example and this example is with simple types like string and number now let's see how we can do it with complex types so again I'm going to comment this code let me also comment this type here let's go ahead and let's create a class and here I'm going to create a very simple class I'll call it as animal okay in this class I'm going to have a method I'll call it as make sound okay and what this function is going to do is it is simply going to log a message in the console maybe generic animal sound right now I'm going to create another class I'll call it as dog and this class it is going to extend this animal class okay and in there we are going to have a method called B and from here also I'm going to log a message okay this is just simple example which I'm giving here all right now let's let me create a function here so let's call this function make creat sound all right and this function it is going to take a parameter called creature and this is going to be of type animal now keep in mind that this dog class is also inheriting from this animal class okay so when we will call this function let me call it here to this function we can pass an instance of animal class or we can also pass an instance of dog class so for example let me create a variable let me call it as animal equals new animal okay so to this make creat a sound I can pass this object of type animal and then let me also create an object of type dog so I'll create a variable dog equals new dog and now let me again go ahead and let me call this make creat sound and to this I'll pass an instance of dog all right so you see in both the cases we don't have any errors so when this function will be called for this creature parameter since it is of type animal we can pass an instance of animal class or we can also pass an instance of dog class because this dog class it is inheriting from this animal class now inside this function let's try to call creature. Bark you see we have an error here because this creature it can store an instance of animal type also but there we don't have bark method if you see here inside this animal we don't have bark method we have make sound method if I try to call creature do Mak sound here we will not have any error because this animal class it is going to have that method Mak sound and this dog class since it is inheriting from this animal class this dog class is also going to have that makes method right so here we will not get any error but if I say creature dob in that case we will have an error because this animal class does not have that method so here also before calling this method we need to do the type check we need to check if the creature is of type dog then only we would like to call the spark method otherwise we would like to call the make sound method now here I cannot go ahead and use type of operator like this so I cannot say type of creat equals dog this will not work here now why we cannot do it here because here it is going to be an object okay when we use the type of operator on an instance of a class in that case it is simply going to return us object it is not going to return us the class name okay so if I say type of creature and if this creature is storing an instance of animal class it is not going to return animal it is simply going to return all object in the same way if this creature stores an instance of dog class this type of operator is not going to return us dog it is again going to return as an object okay and this is just the JavaScript Behavior so here in this case we cannot use type of operator now what should we do in this case in this case we can use instance of operator so here we can check if this creature if it is an instance of dog class okay so this instance of operator returns true if this variable stores an instance of this do class otherwise if this creature stores an instance of animal class in that case this instance of will return false so basically this instance of returns true if the variable is of a given type otherwise it returns false so if this creature is an instance of dog in that case we would like to call this creature dob so I'll put it inside this if statement otherwise we will simply call creature dot make sound okay and let's actually write it inside the lse statement all right with this if I save the changes you see when we are calling this make creat sound and when we are passing animal we are seeing this message generic animal sound and when we are passing an instance of dog we see this message so here we are again guarding the type using instance off so we can use this instance off for type guarding when working with classes again let me go ahead and let me comment this code and let's see another type guard now let's say we have an interface and let's call this interface user in this user interface I have the name property of type string and I have an email property also so of type string okay now let me go ahead and let me create a function I'll call this greet user okay and this function it is going to take a parameter of type user and inside this function what I want to do is first of all let me make this email as an optional property okay so this email is an optional property in this user interface this name is a mandatory property so whichever class will inherit from this interface SP it will have to provide the implementation for the name but this email is optional so now here inside this function I'll use this console.log statement and there I want to log this message here let me use template it syn text and there I want to log the message hello and then Dollar in the curly braces I'll say user do name your email is and let's also try to log the email of the user so for that let's say user Dot email okay now let's go ahead and let's call this create user function and to this function we need to pass an object which will have a name property and it can or cannot have email property because email is optional here so for example here if I pass name property let's say John okay you see we do not have any error because the email property is optional and again let me call this greet user and let's pass name as Mark and let's pass email as Mark gmail.com all right let's save the changes and you see we have this message hello John your email is undefined and hello Mark your email is Mark gmail.com now here we don't have any error but if you see for the email it is logging undefined and this is some unexpected Behavior which we might want to avoid here in place of interface we can also use type okay so that is also possible and we will have the same behavior if I save the changes still you see the message is hello John your email is undefined and hello Mark your email is Market gmail.com so when we are not passing the email we are not getting any error but when we are trying to write user. email we are seeing this result undefined and this is not something which we want to do in our real world projects so here also we can do the type check now here we cannot use instance off because for an interface we cannot create an instance and here this user it is of type type it is not a class it cannot have an instance okay here we are specifying a type to which we can assign an object but that object will not be an instance of this user type in the same way if we use interface we cannot create an instance of the interface and that's why we cannot use instance of in this case then in this case what should we do what we can do do here is we can use another typu so again I'll write if statement and here we will check if email property if it exist so for that we can use this in operator and then we can specify the type so I can say user and here instead of using the type name we need to use the variable name which in this case is user with lower case U okay so if this email property EX exist in this user in that case we would like to log this message where we will also log the email so I'll cut it from here and paste it inside this one otherwise we will simply print the username so let me copy this console.log statement let's paste it here okay and it should be back T actually okay with this if I save the changes you see when the email is not passed in that case it simply says hello John otherwise in other case where the email is there it says hello Mark your email is Mark gmail.com so using this in we can check if a property exist in a given type now here we are not using type name instead we are using the variable of that type here we are using the variable of this user type and same thing we can do with interface also so instead of type if I use interface in that case also it should work here I'll simply remove this equ to and let's save the changes and it should still be working so these are some of the type cards which allows us to save the types we talked about this in operator which acts as a type guard in case of an interface or type we talked about this instance of which also acts as a type c in case of classes and we also talked about this type of operator which X as a typ guard in case of simple types this is all from this lecture if you have any question related to typ guards then feel free to ask it before I wrap up this lecture I also want to mention that you can also create your own custom type cards with some more complex Logics based on your requirement but that I'm not going to cover in this course because that is something which we rarely do but if you want me to cover that topic also please let me know in the comments and I will record a lecture on cust type guards as well this is all from this lecture thank you and have a nice day
Info
Channel: procademy
Views: 359
Rating: undefined out of 5
Keywords: typescript, data types, configuration, classes, objects, ES6 features, decorators, tupescript tutorial, complete typescript course
Id: QToF-_6vwKY
Channel Id: undefined
Length: 16min 44sec (1004 seconds)
Published: Thu May 23 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.