0-60 WITH TYPESCRIPT AND NODE JS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
my name is Bowden Kelly I worked at Microsoft I'm a program manager working on JavaScript tools including typescript nodejs and other tooling support in Visual Studio and Visual Studio code but today we're looking at specifically how to get you from 0 to 60 with typescript in node.js we only have 25 minutes so we're gonna go kind of fast it'll be very demo driven if you have questions hold them to the end and I'll try to get them in time if you get nothing else from this session I want you to understand why typescript is worth your time you know there's a lot of tools out there there's a lot of technologies these days for a JavaScript developer to consider and if you take nothing else away you should understand why why typescript what does it aim to do and we'll get to that right off the bat I'm also going to show you how to get productive fast in whatever environment you're currently in and then finally I'm going to show you just a little bit of typescript in action so why typescript we think it's pretty simple we believe that developers should be able to focus on creating amazing things and creating is bold here because that's what we all aim to do with code you know code is just a tool at the end of the day to help us build services and products and experiences to truly why our users but in reality that's not really how we spend our time if you take every activity you do on a week-to-week basis and your development cycles they can fall into three broad categories understanding code this is you know reading the existing code looking up documentation finding bugs maintaining existing code so this includes refactoring and preparing for new features and fixing those bugs that you know already exist and then finally finally after you've done all of those things if you've paid all that tax you can actually write new code and deliver new experiences we found with javascript in particular the larger your code base grows the more complicated it gets and the harder it gets to focus on creation as anyone familiar with Monaco how about vias code so Monaco is where vias code started the idea was we wanted to take an editor environment and put it in the browser and so as such this was all written in JavaScript and we found that as this code base hit three hundred four hundred four thousand lines of code it became really hard to focus on creation and we actually kind of measured we said how long are we spending on each of these buckets and what we found is a vast our time was just trying to understand what our code was even doing then we spent about 25 percent of our time maintaining and then finally five percent or two hours and a 40-hour workweek actually trying to build that that editor in the browser and we said you know this this is not this is not good enough we can definitely do better what would it take what if we could take this split and just build some tools such that minor savings from understanding and maintenance could add to creation time instead and what would that tool look like and it was chasing that idea that we created typescript now what exactly is typescript the technical definition is an optionally type superset of JavaScript that compiles to plain JavaScript but I've always found it easier just to show rather than tell so here we are in a JavaScript file this is a random javascript file that we took out of a random project and to get started with typescript to see what typescript does all we're gonna do is add a single comment and it's going to be TS check at the top of our file and what this is gonna do is it's gonna flag this in vs code and this is you know vs code by the way if you're unfamiliar you should check it out it's a great editor but if you just put TS check at the top it's gonna flag this file and say hey I want you go type check this JavaScript for me you know do nothing else just run the typescript type checker and tell me if anything looks off and right off the bat you see we have some red squiggles so this is actually not even part of the demo but z object I guess that's a typo my bad but a type so it's gonna look at all these things and see what makes sense or what doesn't make sense and in this case the Z object they don't know what that is and so they flag it and in fact it was a typo it was a mistake so we can delete that out we could look at the next mistake argument of type this string literal value in read-only is not assignable to the parameter property descriptor and so what's happening here is javascript has types it is dynamically typed so they can change and they're not necessarily enforced ever but they do have types types exist under the scenes and that's what typescript looking at and so if we look at this defined property method we can see that there are in fact types that javascript expects at runtime and if we look at this property descriptor there are a limited set of options that you can pass through and anything that isn't in this set this is going to get ignored by JavaScript at runtime it doesn't care right and so we're gonna look at this we're C configurable and numerable value and writable and we can see that back in our code we used read-only so probably what we intended was to say writable false or actually true and you see our error goes away but what would I have been a runtime again if I pass in read-only into this method it's gonna look at it it's going to see that it doesn't match what's expecting that's gonna pretend like it never saw anything and so now you have a misconfigured object your method it may be behaving in a way that you didn't expect and you don't even have an error to point you to the right direction where where your code went wrong and that's what typescript does it points you in the right direction here we have another mistake where we see operator greater than cannot be applied to some function and a number if we look at ship weight sure enough it's a function that returns the parse int of some text so probably what we intended to do was call this function but we didn't write and this is this is a common mistake I've done this thousands of times but you won't catch this until runtime and in fact that runtime what's going to happen when you compare a function and a number it's false it's not an error it's not true it's false and so this code is going to be misbehaving you will never find that you're you know shipping weight is over a hundred it will always return false and you'll have no idea why your codes misbehaving typescript can help you save you from these little mistakes but this is just JavaScript right we haven't done anything to change what's going on here typescript is just looking at your existing JavaScript because typescript is a superset of JavaScript but what else can we do with typescript well we can start adding types in this function we have an email address parameter and typescript saying this is an inny and so right now it doesn't know anything about this parameter but we can tell it we can say hey I've got this comment here that says it can be a string or a string array so I'm going to use a J's comment because again we're still in a j-style I'm going to say this is a string or a string array and now typescript knows from this J's comment that we want this to be a string or a string array and now I can continue type checking the rest of your code with this assumption that this is what you're saying it is and here we find a mistake where we have misspelled trim because Trin is not a function off of email address and so basically what you're seeing here is typescript is just JavaScript typescript is just additional tools to help you write better JavaScript to take care of the little mistakes and let you focus on what you're actually trying to build and so where are you supposed to take away from that quick demo really you can start using type checking JavaScript today it's very simple in vs code all you have to do is out of comment to the top of your file using TS check will get you started fast you don't have to deal with configuration you don't have to deal with config files or build set ups all you have to do is add that comment and then you can slowly start adding jsoc comments with types in them to experiment with what types would be like what is it like to work with a type system you don't have to jump in all at once so you get it you see you can add a type system type checking to JavaScript but does it really work a lot of people think that you know I'm fine without type checking it wouldn't really help me that much well for the skeptics out there there has been a empirical research on this where they took 400 code bases on github they looked at bugs that made it into production and then they went back and applied both slow and typescript to those code bases to see if a compile time type checker would have prevented that bug from ever making it to production and they found that 15% of those 400 bugs would have never made it into production and been caught by a type checker and so it works type systems work so so you saw how we can start type checking JavaScript but type scripts more than that typescript is a superset and it really allows a lot more features than you just saw and so to show you how you can convert an entire existing Express code base I'm gonna take this simple app which is a basic Express app it's actually a pared down sample from a QuickStart and basically it gives you a boilerplate for a node.js Express application it's got some basic templates it's got authentication using passport you know I can login and it's really just a starting point you know many people use these to get started with their applications these days and so this is what we're going to start with and I'm going to convert this JavaScript code base to typescript just to show you how easy it is and some of the things you get once you do and so as you can see we've got a node modules folder a node modules backup folder because I'm very paranoid about having internet during demos you've got a source folder a lot of JavaScript files in here and then your basic config files and so the first thing to do to get going with you know the full-blown typescript is you need a TS config and so I'm a type PFC in it from the integrated terminal in vs code and it's going to generate me a TS config file and we're going to see in this TS config file is a ton of options right but these are all commented out these are basically every option you could pass into T as config with an explanation of what it is and so it's very useful for getting familiar with what your options are but we already know what we need and so I'm just going to delete this and cut straight to the chase we're targeting node so we can use es6 commonjs is fine we want to use a loud J s and what this is going to let us do is pass both JavaScript and typescript into the compiler and I'll show you what that means in a second we didn't want a out directory and we'll call this disc for distribution and then finally we want a module resolution to be node and this is just going to tell the types of compiler I'm in a node application I'm targeting a node environment you should do module resolution in the same kind of way that I would expect in node and the last thing I'm going to do is I'm going to include my source file as you see here I have a source directory and that will basically set the route in which typescript consumes source files and so now when I run TSC which invokes the typescript compiler you will see that I made a mistake oh you're right thank you so this is just globbing pattern and I reversed that on accident so we're going to run it you're going to see we now have a dist folder inside this disk folder is the same thing we put in we just passed in JavaScript files and we got out JavaScript files and you'll notice these are exactly the same which is good so we can now convert we have our compiler set up we can now convert our first file from jazz to TS and once we've done this we can now you know write typescript as we would expect where we can add type annotations inline to functions and then when we call the function if we don't pass in the correct type it will complain right we are now in a type script file a types of environment the compiler is checking this by default now but notice the rest of my files are still JavaScript so I can now run TSC again and it will take all of the typescript files in this source file convert them to JavaScript and we'll take all of the JavaScript files and just basically pass them through the compiler and it will put them all in my distribution folder so that I can still run my app so now I can still do node and this time we'll go from dist and we'll put server and that's not it and fire it up and you'll see that it is in fact still working as we'd expect nothing has changed so this is the part where if you have a large project you might want to go file by file one file at a time convert it to typescript do your work and make it the conversion in a piecemeal fashion but because this is a small project and there's only a handful of files I'm just going to go ahead and convert these all to TS just so you can see what that conversions going to be like and so we're gonna run TSC again and this is where you start to run into the first kind of friction from converting right we're gonna get a couple of errors and you see a bunch of them or cannot read Eclair this block scope variable passport right and basically what's happening here is if we go look at passport ts we can see we've got squiggles on our imports and this is a kind of complicated subject if you dealt with modules in JavaScript before you know that it's a pretty deep rabbit hole and so I'm not gonna go too in depth here but basically this this code is written and require using you know common j/s what we need it to be is an es6 so the typescript compiler can understand it and then return it back to commonjs and so to do that we can just use this handy reg X that I have in this sketchy unsaved notepad file and what this reg X is going to do is it can take all of our import statements and convert them to the es6 import star syntax so when i do that you'll see it highlights all of my imports i can go ahead and execute that and it's going to replace them all in line and I now have import star as passport from passport and you see the types of compiler is now happy the other thing I have to do is if I change my imports I also got changed my exports and so we'll do that real quick - good make sure we don't change anything in jQuery that would be bad and all of our exports get changed as well now this isn't a perfect conversion this was just a real quick regex I wrote right you know before this and so there's a couple places where it doesn't do exactly what we want for example when we're trying to export our model we use modules export instead of export equals or exports equals rather and so we have to go clean this up by hand but you could write a much better you're ready regex than I could and make this actually work and so we're going to switch this to export default user and you'll see why we want a default in a while and then we also need to switch this module export to export app export equals app there we go so now we're going to go ahead and check our problems list to see where our remaining problems are and it looks like we've got one more error again this is another module thing because of the way expressed validator exposes itself in in their module we have to use a slightly separate syntax for the module this is pretty rare but Express validator is the one that you'll experience in a node project where you have to say import Express validator equals require instead of from Express validator again kind of a nuisance but it comes into this whole inherited module problem that we have so now let's look at some of the remaining errors we have and so this one will tell us that property ID does not exist on this type which is an empty object and if we look at this we can see that you know serialized user has a full function body and if we look at that this is actually a DTS file that we have hiding in the project and this is where I have to to lie to you a little bit I went ahead and downloaded all the DTS files for this project ahead of time again for internet reasons but basically what happens here is if we go to our package JSON we can get the type definitions for just about every single node module by going to at types which is basically a community it's on github that just contributes all of their own Taipings to a community and we can download them by using the add type scope on NPM and so when I say at types / expression session I'm getting the DTS file for express session and you can see I have a number of DTS files that I've gone ahead and grabbed and all of these are imports that I use somewhere in this project and what this does is in my node modules folder you will see I have an @ types folder and in here I have a DTS file for every single one of these which contains the types which will let me type check the code this is really great because this is basically free value right typically when you're using a type checker you have to provide the types for them to check when you use a DTS file someone has already gone and done all of the work of adding those types for you and you just get to benefit from that labor so that's great so we're looking at this and we're saying okay well there's a problem here ID does not exist on this you know user but this is our user model this is the thing that you know we defined use for Mongoose right and basically what we need to tell type script here is this is a little more specific than just an empty object in fact it is a mongoose document and so we can import document sorry you can import from mongoose document which is a type again that has already been defined for us if we look at that we can see this is a DTS file again and someone has gone ahead and defined all of the things that exist on a mongoose document and now we can say this user is actually of type document and that that error will go away but not all of the errors go away and if we look at ok we have another problem here where we're importing user incorrectly if we right-click and go to definition on this user we see we just end up in this file but not on the actual user we export and so the issue in this case is because we use the default export we have to alias the import so we say default as user and then we're all better anyway it's back to our back to our user model if we look at this user model we'll add document here again and we'll expect to resolve this error except in this case it doesn't work and that's because compare password is a method that we added onto our user model in Mongoose and so we've added this custom method it doesn't exist on the document and so we need some way to extend document and say you know this isn't just a document this is a user document and so what you can do is you can create a type in type script so we'll export type user document and we'll say that this is a mongoose document and some additional stuff and what this is is an intersection type this ampersand basically says i have one type that i want to start with and i want to throw more stuff into it to create some new type which we'll call user document and so we'll add compare password here and we'll make it an innie just for now and when we go back to our document and we make this now a user document oh we gotta import it first sorry wrong place when we now make this a user document you'll see that our error goes away and indeed if we look at this user we can see that we have the base document stuff on it like ID for example but we also have our function compare password which is of type in E and so we can actually do much better than this because when we defined this model there was a bunch of stuff in it right we have you know profile which has a bunch of strings and password and password token and so again back to my sketchy notepad we can grab the type and type out exactly what we want this type to be it'll go ahead and format this real quick and now when we refer to it now that we've added you know all of the properties that exist on this type when we actually use it we're in passport we can see that we have access to all of those things so if I look at profile we have profile and we can see all of the properties that exist inside profile and so again typescript is just helping you here it's telling you what your options are what's available if you make a mistake and try to you know do something that's not there it's going to tell you this property does not exist on this model that you created and it's going to give you basically the help you need to focus on what you're trying to build let's see last one this is also an import error where we're importing user and this needs to be a default and with that we should be done we've now converted all of our files to typescript we can run TSC and see that it does compiled to you are distributed folder and it comes back clean there's no errors if we run node on that server and we started up we can see that our application still works as we expect right but now we're in like a fully typed environment we're not fully typed yet we're in a type script capable environment so we can start adding types wherever we want and so from here on out you can use typescript or types when it's helpful and ignore them when it's not and so if we go look at user TS this controller for example you can see that we have requests and responses all throughout this file where we don't have types yet and so if we want to we can import from Express request and response and now we can add these types in line and so what this does is if you look at you know before we add it if I do request dot I get nothing right our editor knows nothing about this thing but as soon as I tell it what it is and again we're taking advantage of types that other users have already defined for us if we look at this we can see that there is really a lot of work that has been done here that we can just take advantage of right away when we start using these things we now get great help great tools great support if we make mistakes the compiler is going to catch it if we just want to you know write code and see what the you know functions do or their signatures do you can get all of that right in your editor and so you don't have to flip back and forth between documentation you don't have to spend your time trying to figure out what those methods are that you can call you can spend more time actually doing the work you want to do that looks like that's about all the time I have I want to call out that this is a tiny sample taken from a larger sample if you go to Microsoft slash typescript node starter this is a repo that we maintain so that you can see what a node and type script repository looks like and look at other best practices like testing and CI and setting up vias code with tests JSON and debugging configurations all of that stuff lives in this repository we don't have time to go over today but I encourage you to check it out if you're interested final kind of kind of takeaways I encourage you if you've never used the type checker before download via skoda throw at TS check at the top of your file just to see what happens you may be surprised and find that you have a couple bugs lurking it also may be totally clean the worst that could happen is nothing right I also would encourage you to think about adding typescript to any of your current workflows because it really works anywhere you can lay it on top in about what 10 minutes we just added it to an Express application but you can really add it to any kind of node project you're using today and finally the point of all of this whether it's using node whether it's using typescript any of these tools is to help you focus on building cool stuff you know services products experiences for customers and I encourage you to think about that next time you're working on a project how can I be more productive we think typescript in node can help you do that thank you [Applause]
Info
Channel: Coding Tech
Views: 58,636
Rating: 4.9073758 out of 5
Keywords: typescript, javascript, node.js, nodejs
Id: vxvQPHFJDRo
Channel Id: undefined
Length: 25min 31sec (1531 seconds)
Published: Sat Jan 20 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.