TypeScript Classes Tutorial | TS for Beginners Lesson

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome I'm Dave today we'll learn about typescript classes implementing interfaces and much more I'll provide links to example source code and all resources in the description below I've also recently started a Discord server and I've provided a link for you to join in the description below it's a great place to post any questions you have about this video and to chat with other web development students too our starter code today is the code from lesson five this is lesson six I'm just going to select all with control a it backspace to delete all of the code we have in the main.ts file I'll save that I'd also like to highlight that we have the index.html file inside of the build directory and I've changed this from the last tutorial because we had an example there now I've just got it back to looking for the main JS file that will be compiled and saved into the JS folder under here and it just is named example so that previous code in the index.html is gone okay we're talking about classes today and we've got a lot to cover so let's look at a basic class I'll just say class and we'll call it coder and then inside of the class properties and methods are called members so I'll put a member for the class and this is a property called name and I'll say it's a string type you can see that typescript doesn't like this let's see what's wrong when we Mouse over it says the property name has no initializer and is not definitely assigned in the Constructor so we do need a Constructor so I'll go ahead and start with a Constructor here and then we want to say this is name and it's a string which is kind of redundant isn't it and then inside of there we're going to have this dot name we'll set it equal to name so when we look at this we think how could we make this simpler and we'll talk about that in a second but first if we don't have the Constructor typescript didn't like what we had up here so if I just remove that because it appears to all be right here I'll use Ctrl X to cut it out typescript still doesn't like this now when I Mouse over it says property aim does not exist on type coder so even though it seems redundant this is actually what we need now we will look at another way to do this in a moment but I just wanted to give the basic structure here that you do need the property to exist in the class as a member and then you also need to name it here in the Constructor okay now let's take this example a little further so after our name which is a string type let's put in music as another property that is a member and we'll say it's also string and then let's put in age and that will be a number and finally let's put in Lang and that will be a string and that's abbreviation for language is what we're going to put there okay after we've done that we need to add all of these you can see we have red squigglies for each of those so we need to do the same here so we'll say music is a string and age is a number and finally Lang is once again a string now it might be easier to read if you had more of these if you just break them out onto separate lines and we can do that we put a comma after each one in the Constructor parameters here and then I'll put the parentheses on the following line I'll go ahead and save just to get some formatting you can see typescript still says we need to do more and that's because we also need this dot name to equal name which we have but we need to do the same for the others I'm going to do shift alt and the down arrow three times and after I've done that I can select name Ctrl D to select name twice and change this to music and I'll do the same for age and finally I'll do the same for laying well I didn't select the second one here let me try that again there we go so this does seem very redundant but here we do now have our structure we have added all of these members to our class and then the Constructor accepts those as parameters because they could be passed in when we instantiate the class and that's why they're here as parameters and then we actually assign the values now for me I really like to keep things dry I don't like all of this redundancy and fortunately there is a way to avoid this now we can add what are called visibility modifiers I've also heard these referred to as data modifiers or even access modifiers but the official docs say visibility modifiers or visibility members so let's go ahead and put that here by default all of these properties and if we had any methods would be Pub public but right now we don't have to say that but we can explicitly say they are public so I could put public in front of name but you can see now it doesn't like what we have now it says it's a duplicate and that means we can just remove the one up here now typescript's happy again so if we go ahead and add these visibility modifiers to each of these in the Constructor params then we don't need these up here so let's look at what else is available to us we could have music and besides public we also have the option to make this read only but you know what I think I'm going to do of course I need to remove this up here I'll just remove all three so I don't have to keep going back I think I'm going to go ahead and make music public but then I'll make this actually public and read only because you can do both so that means once the name is assigned it cannot be changed and then of course this is explicitly public as well when we talk about the music type let's make the age private and that means it can only be accessed in the class and we'll look at an example of that as well and then let's make the language protected and that is our last option there so we're looking at all of these different modifiers onto our data but this makes it a little less repetitive our code is a little more dry so even if you just use the default of public you won't have to type it twice if you do it this way now before I go further with these modifiers I do want to show one way to avoid those errors it would be very unusual but say you were adding a property that you did not want to instantiate right away maybe a third-party library or something like that is handling some of this for you either way I just want to show an example of how you could do this so I'm going to say let's just say second language second laying and we can say string and then you're going to of course see this red squiggly and it's going to say it has no initializer but we can add an assertion here and this means that we are asserting that we know what we're doing and we're just not going to initialize this right away so you can add this if necessary again beginners I recommend staying away from this but it could come up sometime in the future and it would be a nice thing to remember okay I'm going to save our class and then underneath this we can instantiate it so I'll just say const and I'll say Dave will be an instance of our coder object set this equal to a new coder and inside I'm going to pass in the name argument and then we need a music argument let's say rock and then we need an age argument and I'm going to say 42 not that it's my age but hello Douglas Adams if you're familiar with his books and now we can add our final RAM and this would be say typescript but what if we want to make this optional but we can do that because Constructors are a lot like passing params to functions so instead of providing typescript here let's make the last one language optional by adding a default value here so we can just say this is typescript and now you can see typescript is fine with me creating a new instance of coder Named Dave without providing that fourth parameter and now remember age is private first name and music are both public even though name is read only and Lang is protected now what's the difference between private and protected well it can be accessed or I should say Lang can be accessed inside of the class but it could also be accessed inside of derived classes if we were to extend this to a subclass we could still access Lang but we could not access a age because it's private and can only be accessed inside of this class so I'm going to scroll up and add a method here and I'll make the method public and I'll just say get age remember age is private inside the method we'll just say return and we'll give a template literal here that says hello I'm and now let's say this dot h which should retrieve the age this is fine because we're inside of the class so even though age is private we can access this value inside of the class and we can just call the get age method to of course return that value however let's look at what typescript knows about our class and we can say let's first let's do console.log I'll say Dave dot get age and it should be fine with that and it is but what if I had console log and now I say Dave and I just try to access the property the member of the class age it doesn't like that it says age is private and only accessible within the class coder so we can't do it that way likewise I'll copy this down with shift alt and the down arrow and let's try to access Lang and again typescript says no I Mouse over and you can see property Lang is protected and is only accessible within the class coder and its subclasses so while we can access a method that accesses the age value inside of the class we can't access those properties directly outside of the class I'm going to go ahead and save our typescript file and then press control on the back tick to open up a terminal window type TSC and dash W for watch so it compiles and I've got a couple of Errors of course that we put in there on purpose but we have compiled that now so let's go to our index.html and I'm going to use live server to launch that and you can see it launched here on the left I'll drag Visual Studio code over to the left window as well back to our main TS file and then Ctrl B to hide the file tree I'll click on the browser and I'm going to press Ctrl shift and the letter i to open up Dev tools and we have the console here so I'm just going to drag this up and we can see of course ignore the live reload enabled or I can just clear this out and I can refresh the page and we get hello I'm 42 which is get age and then we get 42 in typescript so remember we're going ahead and compiling this and even though typescript the compiler doesn't like what we're doing it is still legal JavaScript so typescript lets the page go ahead and compile and of course we could change that in our settings so it would not compile if it didn't like anything but it lets you gradually adjust your code and refactor your code to typescript so it is working and it shows the 42 in typescript even though it doesn't like that here I'm going to go ahead and comment out these two lines that typescript doesn't like but I'll leave them in here just so you could uncomment them and see those in the source code if you download it from the course resources that are linked in the description okay after that let's go ahead and extend a class so I'm going to create another class and I'll call this class web dev and I'll say extends coder and then inside of this class we should have a Constructor and then of course we'll have our curly braces as well we need to pass several things into the Constructor but I'm going to add a new property also so I'm going to say public and put computer and this will be a string I'll put a comma because underneath this we need to add what we're bringing in as well from coder that we extended and I'm just going to bring in name age and number so I'm not going to bring in the language that has a default value already and then when you extend a class like this before you assign anything here such as this dot computer equals computer which is what we would do we need to put something in front of that and if you're familiar with JavaScript classes as you can see typescript wants to help us we must put in a call to Super so let's put in our super and then it needs to receive everything that we are receiving from coder so it will get name music and age so again remember super here needs to come before we try to assign anything else like this dot computer so if I put that above typescript is not happy so I'm going to undo that and make sure that assignment is after the call to Super now notice we did not bring in the Lang member that we had above encoder but we extended coder here and Lang has a default value of typescript so let's go ahead and add a method here and we'll say public and then get Lang and we'll return a template literal and I'll say I write now let's put in this dot Lang and let's see what happens when we call this after we instantiate a web dev so I will come down below this and I'll say const let's call this instance Sarah put this equal to a new web dev and the computer is first so we'll say Sarah has a Mac or Sarah's name is Sarah and she listens to Lo-Fi and put in an age of 25 and you can see typescript is now happy we've passed in all the params that we needed to for the Constructor so now that we have done that let's go ahead and say console.log and call Sarah Dot get Lang and when we save it should recompile and yes remember we commented out a couple of lines so we have the get age up here it says hello I'm 42 but below we had surrogate Lang that says I write typescript so notice how we didn't put any of those modifiers on name music or age here so what about accessing those now will they be public by default let's find out I'll type Sarah and then let's try to access age but typescript says no age is still private and it's only accessible within the class coder so let's go ahead and try to access the protected property because that can come down to subclasses right so our protected property was Lang if I remember right let me scroll up and look yes protected Lang in our coder uh Constructor so let's switch this to Lang because now we have a subclass whoa it still doesn't like that does it we Mouse over it says property Lang is protected and only accessible within the class coder and its subclasses note here even though this is a subclass we're not within the class but this is a subclass here our web dev extends coder and within the class we could access the protected Lang member the property from the coder above that we extended to web dev I'm going to comment out the two things that typescript did not like again here and let's move on to the next example and I'll put a little bit of a line here in the code as well let's see if we can just leave that in yes and that will just draw a dividing line because now I want to talk about applying an interface to a class where you could say implementing an interface to a class so I'm going to create an interface named musician and we have looked at interfaces before as we covered objects in this series I'll give this interface several properties a name which is string and then let's say instrument which is also a string and now let's give a method we'll say play that's going to receive an action which is a string and it's going to return a string so a simple interface with two properties one method now we can implement this to a class so I'll scroll up a little bit more and then after this we'll say class and we'll make this a guitarist and we'll say implements with the keyword implements and then we'll say musicians so we name the interface now inside of this guitarist already has a red squiggly line so we can see what it wants it says it's missing the following properties from type musician name instrument and play it's going to need all of those so I'll say name and that will be string and we'll have an instrument which is a string and now let's go ahead and provide the Constructor and I'm taking the long way on this one but that's okay we'll put inside of this we need to say name actually string and we'll have instrument that's a string much more than that and I would have broken those onto separate lines after that I'll say this dot name equals name and this dot instrument equals instrument nice review there of everything but guitar still isn't happy because it still needs play so we haven't put the method in yet so let's do that we'll say play and then we'll have our action and it's going to be a string and then we're going to return a string so I'll say return and do a template literal and this is going to be this dot name so whatever name is passed in and then we'll go ahead and say whatever action is passed in and after that we'll say the and then we'll say this Dot instrument so this should return a sentence that reads something like Eddie strums the guitar or something like that so here we have our class that implemented our interface and notice if we switch name to number it's going to check against that interface and it says property name n-type guitarist is not assignable to the same property in the base type musician so these do need to match up so we'll say a string then it once again matches so typescript implemented our interface musician it made sure all of the members of the class were there as expected and it's even checking the types back to of course musician here that we defined in the interface so we've got all of that let's go ahead and instantiate one of these guitarists so we'll say const and I'll say page let's do that one you know who Paige is we'll say new guitarist and here he is Jimmy Page if I could spell Jimmy correctly and yes he has a guitar for an instrument which kind of makes sense that's that's a kind of a duh moment isn't it after that let's go ahead and say console.log and then we'll say page dot plays and we're going to say strums for the action and this is a good example because typescript caught my mistake I said plays I wanted to say page plays the guitar but play is the method not plays so if I remove that s now it's accurate I can save and we get Jimmy strums the guitar over in our console I'm going to scroll for some more room and once again put in a divider in the code because we are switching topics although we're still talking about classes I'm going to create a new class here and just call this peeps inside of the class we're going to create a static member which would be a property here so we'll say static and this would be count and count is a number I'm going to set it equal to zero and then I'm also going to create a static method that is also a member of the class so I'll call this get count and it's going to return a number and then we'll return notice what I do here I don't use the keyword this I refer to the class itself peeps dot count so what a static keyword does mean it means that count does not apply to any instantiation of the class it applies to the class directly itself so we'll be keeping track of count in the class not in any one instance of the class and then git count can be called directly on the class as well and so that's why I'm accessing count directly on the class keeps here now let's go ahead and give a public property so I'll say public and we'll create an ID and this will be a number type and after that we'll use a Constructor and we'll say public here as well and we'll receive a name param and this will be a string and then inside of the Constructor we'll say this dot name is equal to name and then we're also going to say this dot ID that we used above is equal to plus plus not count so what does the plus plus do when you see it on the left versus the right well it's going to make sure that our count increments first so what we're going to have is an ID of 1 instead of an ID of 0 when the first instantiation of this class is created you'll see how this works and this is just normal JavaScript here we're not saying anything specific about typescript but if I put the plus plus over here our first ID would be zero so I'm putting the plus plus way back over here on the left so our first ID is one okay so now I'll scroll up and we'll instantiate peeps for a few people so let's say const John I'll set him equal to new heaps and I'll pass in John and then I'm just going to shift alt in the down arrow a couple of times select John here Ctrl D to select the second John and of course make a Steve and then do the same thing here and let's make an Amy so now we've got three instances of Peeps and we've created John Steve and Amy so let's log some things to the console first of all let's console log our peeps count and this should tell us how many times the class has been instantiated to create objects so let's see what we get we get three so we've created three if I remove Amy just Ctrl X and then Ctrl s to save we get two so we're incrementing our count on the class peeps for every object that is instantiated from it that's kind of cool what about the IDS so let's go ahead and say console.log and let's get the ID from Steve so what is his ID he's created second and that's what we get we get the two of course we had peeps count three at the bottom we get two let's get uh Amy's count so console log we'll say art I said count let's get Amy's ID her ID is three because she was created third and so you would expect John to have an ID of one let's take a look John dot ID and save yep John's ID is one so the main thing to take away here with using the static keyword of course is that it applies directly to the class and not to any specific object that you instantiate with the class okay one more example I know we've covered a lot but let's fit in something about Getters and Setters because you might see this in react when you're used to working with the use statehook for example or you're just wanting to keep state in an object you instantiate so let's go ahead and create something like that let's say class and I'll say bands here and then I'm going to set a private member and I'll call it data State this will be our state that we're keeping track of in bands and it's going to be a array with string data okay after that I'll say Constructor and we're not going to pass anything in but this dot data state can get initialized as an empty array and that's fine let's after that let's put some methods and we can put public or private on any method too so I'll say public I'll say git which is a keyword and I've seen data and then after that I want to say this getter is going to return an array that has string data in it and that's exactly what we're going to return because we're going to return our state which is this dot data State now if I just leave it as this that makes this read only because there is no Setter but git is a special keyword that we can use in JavaScript again this isn't just typescript but in JavaScript to get our data that we have inside of our state here that is private right here so being read only I would want to initialize this with some more data here but just to keep moving let's go ahead and create our Setter as well and set is another special keyword that we're going to use and we'll use data once again now I'll say value is an array full of strings so that's what it should accept now let's think about what we want to do to check to make sure this data is correct inside of our Setter so I'm going to say this needs to be an array full of strings and we can check that by saying if array dot is array and then we can pass in the value so that checks to make sure it's an array how about checking to make sure every value is indeed a string inside and I just gave the keyword there we can say value dot every which is a method that you can call on an array a higher order function if you will and then let's say for every element we're going to check type of element and we'll make sure it is equal to string so this would be true or false is what every would return after it checks every element and every element needs to match that in order for every to return true so now that we have checked everything we need to we can say this dot data state equals value then we can return I'll look at this return in just a second to see what else it might do but let's also say here else row new error and we can be specific here we could say param is not an array of strings okay coming back to this return I put it on this line here but what if we tried to just return right here to end this out now typescript doesn't like that let's look at why said Setters specifically Setters cannot return a value so I'm going to undo this the empty return is okay but Setters cannot return a value and let's see how typescript identifies this so if I Mouse over data it says it's a Setter and we're going to set the bands.data and it should be an array full of strings and likewise if I Mouse over data up here this is a getter and it's bands.data and it should return an array full of strings so let's check some of this out by instantiating one I'll say const and here I'll say my bands and I'll set this equal to a new bands now I'll say my bands.data and here I'll put an array and we'll say Neil Young some good classic rock maybe Led Zeppelin so I'll just say Led Zep and then underneath that we'll say console.log and I'm going to log my bands.data that's how you use the getter right there is just to say dot data so let's save and see what we get we've got an array it returned the data Neil Young and led Zepp is in the array so after that let's use the setter so here I'll say my bands dot data once again and I'm going to set it equal to an array once again and I'm going to spread in mybands.data that we already had because we used the setter right here mybands.data equals uses the setter so we've already got that in there I want to add one more band I'm going to add ZZ Top okay now that we've done that let's just copy this line down again so we can use the getter to get that data once again and when we save now we've got an array with Neil Young led Zepp and ZZ Top so what about that error we put in there we were checking some things to see if it received the correct data when we attempted to set it so let's try to use that Setter again we'll say my bands dot data equals Van Halen what typescript knows it says this is no good String's not assignable to the type array that should have string data that's not going to work so let's go ahead and make it an array and I can do that by putting the brackets around it now that would work but what if we had the string Van Halen in and the second element was 5150. once again typescript says no go number is not assignable to type string so everything is working there but we didn't actually go ahead and save this to see if it would throw an error as well so let's do that we save yep param is not an array of strings so we coded our check up here correctly and we're throwing our custom error right here because we didn't meet this criteria likewise if we switch that back to just a string like the Van Halen it would also throw that error remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 18,541
Rating: undefined out of 5
Keywords: typescript classes tutorial, typescript, classes, typescript class, typescript classes, typescript tutorial, ts classes, class tutorial, ts class tutorial, classes tutorial, classes in typescript, type, script, type script, typescript for beginners, typescript lesson, typescript lesson for beginners, classes in ts, classes tutorial for typescript, beginners lesson in typescript, implements interface, typescript interfaces, typescript tutorial for beginners, typescript interface
Id: zQondDhCXDI
Channel Id: undefined
Length: 31min 34sec (1894 seconds)
Published: Tue Nov 08 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.