What's New In TypeScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

tl;dw?

👍︎︎ 2 👤︎︎ u/night_of_knee 📅︎︎ Dec 13 2017 đź—«︎ replies
Captions
good afternoon everybody my name is Anders Hollis Burke and I'm here to talk about what's new in typescript typescript basically is about solving this problem it's about making JavaScript scale I'm sure it hasn't escaped your attention that javascript has seen tremendous growth in the last 5 5 or 10 years but in particular last 5 for variety of reasons you know like JavaScript not just runs in the browser but runs with node.js on the server and runs in a variety of native modes on devices like react native or cordova or what have you on on phones and tablets and really javascript is the only true cross-platform game in town you know even Java that was originally designed to be cross-platform isn't really cross-platform anymore so a lot of developers are writing a lot of apps in JavaScript but javascript was never really designed to be a large-scale application development language it is a dynamic programming language which means it has no type system it was perhaps intended for you know hundred or thousand line programs and now we're writing like up to million line programs and we all know that programs that are that large take teams they take scaling they take a bunch of methodologies that we've already sorta are familiar with in more grown-up environments like say C sharp or or Java so we're we were looking at this this problem about five years ago about what can we do to make JavaScript scale better we basically thought that you know the ideal solution to this problem would be to add to JavaScript those things that are missing for large scale app development you know an alternative strategy could have been let's create a new language and just treat JavaScript as the il of the web and just cross-compile say script sharp or or Java or what have you you know but but you're never going to be best to breed and you never gonna get everyone happy if you're targeting one ecosystem from another ecosystem you want to be in the ecosystem you want to be of the ecosystem and so so with typescript we basically set out to add these things that are missing at the time when we started five years ago javascript didn't even have modules or classes and and so that those were obviously targets but in particular JavaScript doesn't have a static type system and when you think about what it is that powers the rich development experiences that that developers today are accustomed to like things like code navigation statement completion safe refactorings what-have-you error checking before you run your program all of that comes down to having some ability for the IDE to reason about the code you're writing and that ability comes from having a static type system so so typescript effectively is about what's creating a statically typed superset of JavaScript that then compare compiles back to plain JavaScript so in a sense typescript starts with JavaScript and then we add an optional static type system but then when we compile all of the types go away so you're sort of left in the in the development phase of your program with an elevated experience where you have a more grown-up language but your code is just JavaScript and it runs everywhere that JavaScript runs now I said being for the JavaScript community but we also knew that it was very important to be up the JavaScript community and we decided to to write typescript in itself and that means that it is effectively written in JavaScript and that means that our tool set runs anywhere in any browser on any host and on any operating system in fact if someone had told me ten years ago Anders in five years you're gonna be writing compilers in JavaScript I got that that's a good one but but here here we are and it's it's quite amazing how far these JavaScript runtimes have come and how capable they are the chakra runtime that we have an edge or the VA runtime that Google has in Chrome or nodejs it's amazing it's amazing what they can do and we are indeed writing compilers not just compilers we're writing entire I des and development tools in in JavaScript and they work beautifully as you'll see and of course we set from the onset we want this to be an open source project we've been hosted on github now for over three years we started out on cope Lakes but but soon realized that we got to go where the action is and move to to github that's our daily workflow the entire team sits in a team room in Redmond but but basically works on get up we take lots of contributions from the community and it's it's a fun way to work it really is I'm writing more code these days than than I ever have before now if I have to sum up typescript really sort of brings two key things to the table key benefits one is great tools enabled by static types and the other is the ability to use features from the future today which basically boils down to a capability called transpilation let me try to motivate that a little in in JavaScript if you let's say you go back say two years to May of 2015 this was sort of the state of JavaScript back then Eckman script 2015 was just about to be ratified yet on the server nodejs has only just made it to es 5 and most browsers didn't even support es 5 yet and so there's this gap between what you have to target in order to make your app run and what you want to use as a developer and that's what I call the feature gap and that gap is actually it's not it's not a one-time phenomenon it's it's a thing that just sort of continues to a Syst here we are now two years later we're about to ratify es 2017 yet on the server nodejs has yet to get egg Musgrove 2015 modules they're still doing common Jas and you know we've only just gotten to the point where you can assume ignore squid v in in your browser so so this gap continues to be there and in fact it's it's a gap that will probably always be there it's it's gonna take a while for all these old Android phones to to catch up with with the latest and greatest and by the time they do the latest and greatest will have moved so in that gap we can fill this gap by transpiling the latest and greatest version of javascript down to older targets and you'll see me demoing that so so that is the they're sort of those are the two key things that that typescript brings to the table now in this talk I'm gonna do a quick summary of what it looks like to use typescript and then we're gonna go into what what have we done in the last year and where where are we going with the product but so bare baby there's a bunch of people here who who may have not seen the product in use at all and so we're just gonna set that up a little bit um I'm gonna switch to my demo machine here and we're gonna write some code here so I'm gonna fire up Visual Studio code which I'm sure how many of you use Visual Studio code just out of curiosity Wow see your arms yeah wonderful Visual Studio code is our open source IDE I am proud to say that it is entirely written in typescript so everything you see me do here is written in typescript runs on a JavaScript VM Visual Studio code also uses the electron shell which basically embeds WebKit and node and the v8 execution engine and allows you to build desktop apps that way and that's what we're looking at here and of course it runs everywhere on Macs Linux etc okay I just have a piece of JavaScript here it's by inspection you could see it's a function that sorts an array but but who knows what it does because it has no types there's nothing really that says what's going on here we can see there's a parameter called a but we don't know anything about a and therefore we don't know anything about any of the things that are in here they're just all of type any if I hover we do know and we can give you statement completion on there being a function called sort by name but you can pass anything you want to it then hey it's JavaScript you know it's gonna it's gonna blow up at some point but but not yet now what if we could actually say more about our intent well so so let me first rename this to typescript so I'm just gonna rename this file to main TS and lo and behold nothing changes because javascript is a our typescript is a superset of JavaScript so anything you can do in JavaScript you can do in typescript but now you can do more things specifically you can add types that describe what you're intending to do here so I'm gonna for example insert an interface declaration of a person which is a thing that has two properties name and age and then I'm gonna say the array here is actually a person array and once I do that you see stuff starts to light up all of a sudden down here if we hover it says hey if the number five is not an array yep that is true but so let's try and pass an empty array and now we're good there and then we get some errors in here so so let's see what how did we get that error so so a now is of type person array and that means that the slice method we know what it does and it returns another person array so that's the type of result and result then has a sort method because it's an array and sort gets you a callback function that passes you two values that must be persons we can infer and so we can actually push the types from that single annotation we have now strongly typed everything in in this little function and push the types everywhere and so when I'm writing in here and I say return X dot you'll see I get statement completion on what the properties are and since name is a string we know there's a locale compare method and can pass to that why Dodd name and here you just saw we found the error I had misspelled local compare or locale compare it's really III I had spelled the local compare but that was wrong now the checker can confine that error for me so so now you're gonna wonder well where where did this information come from you know how do you know that an array has these methods so if I say a dot here all the methods of array where did they come from well we could try to say go to definition on the slice method here I'll just press f12 and that jumps us into a file called Lib d dot TS this is what we call a declaration file you could sort of think of it as header files for the web or header files for JavaScript it's a file that contains all the type information for the entire JavaScript runtime library and the Dom this is a very big file actually if we go to let's see let's go to the bottom here 21 and a half thousand lines now and these are the 21 and a half thousand lines of type declarations that as a JavaScript Avilla you're supposed to know by by by heart right because where else is it going to come from someone you're typing your JavaScript this is just stuff that you either have to go look up or whatever but now by writing it down and by having a set of tools that understand it we can actually serve it up in context and show you all of this and we can use it to check your code so the cool thing is that we can provide the type information after the fact we don't have to write our code in typescript to get a type check we can actually take plain old JavaScript frameworks and then go write declaration files for them and all of a sudden poof you get a better experience and of course the community has obviously discovered that and and by now the open-source community has collected in excess of 3,000 declaration files for all of the popular JavaScript frameworks that are out there and we now automatically package them up and make them NPM packages that are just installable and we'll see that in later later later in the talk here so let me try now to show you some of the transportation capabilities so let me for example try to use a feature that got introduced in ignore script 2015 which is arrow functions and you'll see that my editor allows me to do it we understand what it is but but let's try and figure out how that actually gets compiled into JavaScript so I'll go back here and then I'm gonna start or create an init and in a configuration file for typescript and then I'm gonna start the compiler in watch mode and now the compiler just sits and whenever I save it automatically compiles my file into into JavaScript so now let me try to open in a different window here well put Minjae s over here oops that's not what I wanted to do what mean done to yes in this window and we won't main dot J s over there and here you see the same code that I wrote but all of the types have been erased you see that we're back to what we sort of started out with right but you also see that the arrow function I broke got translated into a regular function over here because our compiled target is echo script v a Negra script v does not support arrow functions now let me try to add a a class declaration also and let me try and save my file and then you'll see the watch mode the compiler and watch mode behind the scenes automatically recompiles the code and turns the class into idiomatic Egmore script v that basically is the code that you would have to write before classes were introduced and that you may have to write if you want to run on something that isn't yet egg Musgrave 2015 compliant now we can actually play with this and we can bring up our config file and then we can change the target that we're compiling to to ignore script six and let me just save the config file and then you'll see that the output immediately jumps and now it becomes a prescriptive with the types erased right so so basically there's this dial that you can SEP 2 level you want from a single source base you get to use the latest features but you get to run on whatever target down level target you you want okay so that is a very quick introduction to some of the features of typescript now let's try to look at but real real-world use of typescript looks like you I'm sure some of you heard that a couple of years ago we entered or more more like two and a half years ago now we entered into a partnership with the angular team at Google they were working on angular 2 the next version of the angular framework and they were talking about a thing called atscript that was sort of like a superset of typescript and we go hey why don't we work together we can do whatever features it is that you need like they needed decorators and so we go we can do decorator so so why don't you why don't we go away and do that and we did and then they took a look at it they go wow this is great and they decided to write angular 2 in typescript and that's now been ongoing for quite a while in fact they shipped it and now they've also shipped angular 4 which was the next version and 4.1 which which introduced strict null checking and whatever and so there's an awful lot of code now in the wild written in angular and let me let me try and go find some of it here we'll go to one site called angular Expo that is a sort of an expo of a bunch of cool apps written in angular there's a SoundCloud client that was written in angular we could try and run it here and it's sort of a full-featured player for SoundCloud I didn't hook up my sound here but it actually does play the songs and it's it's kind of cool now it also is open-source it's hosted on github here's the repository for for this app and I've cloned that repo on this machine here so so here it is and let's try to let's try to fire up the idea here and take a look at this code in fact well let's first try to run it so I'm just going to npm start in here this comes with an NPM script that automatically sets up a web pack development server what you're seeing it do here is since on the first start it compiles and packages everything web pack is basically this technology that can take a whole bunch of Achra script when a 15 modules and package them into a single file that you then reference so instead of having to download 900 modules you download one file and they could also do tree shaking and do all sorts of cool stuff so so if we built the app here and now let me try go to localhost 3000 and here you see a local copy of the same app running and I didn't really change anything but now that we try and show you what the workflow is like in in an app like this you can see that that in the IDE here you know we can navigate code it's a modern app you know that has import statements and uses classes and whatever we can say go to definition of app module you see that it uses decorators here to to add a whole bunch of metadata there's an app header component which is the header band on by on my app and you see in here there's like this SoundCloud angular 2 title which is the title that we said we see you up here so we could try to modify that and just see what happens with with the workflow so let's try and say hello built here instead and before I press save let me let me do a little window rearranging magic here so we can see all of the all of the players in action here I'm gonna put that window there and I'm gonna put these windows over here and now I'm gonna go back in the editor here and let's see where was our change oops right here and now I'm just going to press ctrl s and you'll see what happens here is webpack picks up on the file change does an incremental repackaging and then auto refresh is the browser so thank you thank you so so we know that we know by experience that JavaScript developers like to be in this mode of just edit and save and immediately watch the changes but of course we have a whole tooling pipeline here that needs to get in the in the picture but all of that has been engineered so that webpack can use our compiler as a transpiler service that can transpile the modules it can automatically be packaged it can automatically refresh the browser and you get exactly the same experience that you know from playing JavaScript but with a much higher level programming language so that's what it looks like to use angular another very popular framework out there is react from Facebook and and the associate react native and I got a another little example here that I want to bring up let me just my machine went to sleep let me login again let me switch to this machine here which is a MacBook also running Visual Studio code over here I want to show you a react native app that comes from a company called art C which is a company that does a fine art marketplace and they do all of their development open source and they built a whole bunch of cool open-source react native components and i i have cloned a repository of theirs for a demo project called omission and and i'm running it right here live in an iPhone emulator let me try to bring that up and in here you see that I'm on on the sort of the home page of this app here and in this home page is actually written as a react component in fact it's this file home dot TSX so so you're gonna wanna seeee this what is this X me we know that T is typescript well TSX is the typescript version of JSX and JSX is a dialect of JavaScript it's it's JavaScript but it also allows you to embed JSX markup so basically you can have code and markup in the same file kind of like script text but but with JavaScript on top instead if you will and where markup is basically like another form of expression element that you can have so so let's look at what that what that looks like in here if we scroll down there's every every JSX component has a render method and in here you see how it just returns markup and in this markup you can sort of switch between markup and JavaScript code very seamlessly so you see how you can composite a ListView and then inside the list where you can have some JavaScript code that runs that then in turn puts other markup in there and you can even define markup components yourself so for example here is a search bar component and we actually understand JSX in typescript and not only do we understand it but we understand the types of the markup as well so you can actually navigate on your markup so I can say go to definition I'll press function f12 on my search bar and it jumps to the class called search bar which implements that component and that component in turn has a render method that in a compositing fashion uses finer grained markup and so it all sort of breaks down that way now now in here I could actually go refactor my my markup so let me try to say function f2 and call this one art finder instead and notice that we changed the name of the class here but if we go if we go back oops let me go what is it we navigate back well we can navigate back to the home page here you'll see that it changed over here as well so when you refactor your markup if you actually refactor not judge JavaScript but also the markup which is which is pretty darn cool let me try to modify my search bar a little bit you see that it has a the text here says search for artist and whatever we'll say hello build here and let me just save and actually I should say both files let me save this guy and let me save this guy over here there we go they did not reload nope okay I think I should have saved both of them at the same time anyway you get the idea here that you you cannot reload your app here and see the mark-up changes reflected in but but that kind of broke for me though sorry about that anyway that's sort of a quick example of [Music] react native another framework that's become very popular of late is a framework called view Jas and I wanted to show you sort of the workflow with typescript and view as well so let me try to go there UJ s okay and in here we have a a small start wet pack on this guy as well in watch mode keep that in the background and then let me start index dot HTML start the app just so you can see what what this looks like it's a little to-do MVC app written using view so I can type in some stuff hello world just and I can check them off but there's a part of the app that doesn't work this clear completed here has no effect so let's go see what's going on with that so we'll try to go back here and fire up code and let's let's look at a code here so this app starts in main which is again modern app that you webpack it has a to-do app dot view that it imports here and this is an interesting file here it's a dot view file and a dot view file has both markup and code in the same file in a template section for the markup and then in a script tag for the code and you could also have CSS in there it could sort of all be packaged together now the reason this all works in here in fact you see that when I hover over it in here I actually get intellisense instead and I'll get statement completion and and so forth this works because someone has built an extension plugged it in and we plugged it into vias code here with the tooling for view and let me try to show you also as part of this some of the work that we did in typescript 2.3 is enables us to understand the pattern use by view when you're defining new components which gives you a great authoring experience you see that in here a component is written by calling view dot extend and then you pass in an object literal that has a components property and a props property and a data property and a methods property and then view mongols all of this together and makes an object out of it and then when it calls methods then this object inside those methods is actually a combination of taking all of that and making it into data properties and computer properties so when I'm in here and I say this dot you'll see that we actually let me scroll up here so you can see a little bit better I say this dot for example to do's you see statement completion here this information actually came from this object here returned by the data method likewise create to-do came from the methods that I had in my methods section of my object literal so typescript 2.3 actually allows you to express that mapping that occurs statically so we can come what this is gonna be in when you're creating a component like this which is which is not a simple thing to do but it gives a great development experience for for writing code in using view let's just try to fix the little bug that the App hat which is that I had commented out this line here so we can say this dot - duze equals this dot remaining and we can just save this will automatically repackage I can simply go back and refresh here type in some stuff and then try to say clear completed and now now that works okay so those are lies it's a whirlwind like three different frameworks that you can use with typescript and I think my point here is a you get that modern JavaScript like workflow but you have an elevated experience where you get all the tooling that that you're accustomed to from grown up programming languages if you will and be perhaps more subtly is that typescript really is in a sense Switzerland for frameworks you know we don't we are not like Affinia ties with a particular framework we really strive very very hard to do a good job of any of the popular frameworks out there we're always on to watch because there's a lot going on in this JavaScript community new frameworks coming online all the time and so view das that was typescript 2.3 we reached out to Evan you who's written that and like worked with him to like make the development experience even even better than it already was okay let me go back to the slides quickly and let's talk a little bit about our release cadence and how we go about developing typescript so in the last eight months we have released four times - OH - one - two - three I've put up sort of like the two major features from from each release here but but there were a lot of new features that happened this this is some of them and then they didn't even fit on the slide but the team boobs really quickly we're actually now we have converged on a two-month cadence and we ship we co ship with Visual Studio code so whenever they ship we ship a new version of typescript and we just snap whatever is done at the time so instead of like trying to determine oh we really want to get these features in we get in whatever is we get in and if you don't get in that train then it gets into the next one the way we work as a team is as I said we're all on github we have a lot of tests that we run in our repo we never accept poll requests unless our fifty five thousand tests pass and if it's a new feature it has to come with new tests as well and whatever pull requests go in they go into typescript app next which you can npm install and we actually have a large portion of the community always running on the nightly build because the quality of the nightly build is so high that you can get away with and that way you have all the latest features but for us it means that we're effectively perpetually in beta there is really no such thing as beta because beta beta happens every night you know whenever whenever we do the nightly build right and lots of people pick it up we immediately hear about issues if there are issues so so in turn this allows us to move that much faster so it's sort of this virtuous cycle you know that just keeps on keeps on going I wanted to show you some of those new features that have gone into typescript over the past eight months and I'm gonna start by probably show by showing you what I what I think is by far the most impactful one whoops let me switch to my demo machine here so in typescript 2.0 we introduced a feature called non nullable types which it's actually quite remarkable if you think about like well let me ask it this way how many of you have ever had a nullpointerexception right isn't it remarkable that we still have no pointer exceptions I mean like after all these years we still we still battle with with nulls Tony Hoare who's now Microsoft Research who actually invented know called it his 1 billion dollar mistake in later in life because it actually like he could document that it at least cost a billion dollars in lost work and whatever and now javascript actually not only has null it also has undefined so this is the two billion dollar mistake in in in javascript and so for typescript to oh one of our big pushes was we're gonna we're gonna make some progress on this problem now the way we went about making that progress was originally in typescript 100 all and undefined were valid values of any type so that meant like any string number whatever you can always assign null or undefined and that of course means that it's very hard to track effects of null and undefined if every type allows allows null and undefined so the really the crux of this work is to say we introduced a new stricter checking mode and in that mode null and undefined are not valid values of any types other than two new types one called null which has the value no the only values no and one called undefined whose only value is the value undefined so their unit types effectively and then we use Union types to combine them so if you want a string that can also be null then you say string or null or a number that can also be undefined or number or undefined you get the you get the idea okay that's it here's irse here's a little piece of code I am gonna load up my config file and then I'm gonna turn on strict checking save that config file and now when I go back here you'll see that some errors appear that weren't there before and these are all related to nulls and undefined so let's try to chase them down and see what we can do to fix them first thing is we notice that we get complaints about the variable count not being assigned before it is used now what's what's going on here is that the compiler is now performing what we call control flow based type analysis and that means it the compiler analyzes all possible flows of control in your code and then at every point where you reference a variable it determines whether at all of the possible preceding code paths this variable has been assigned and in fact it analyzes what type the variable gets as a result of all the thing all of the all of the code that preceded you to that point right so if there was a check for not equal to null well then we know that we can remove that from the type as we as we go into that reference so so in a sense as a side effect of the null and undefined work we get definite assignment checking and here we see you know we've discovered that you didn't assigned a count so now let me naively try to fix that by saying count equals zero inside the for loop which obviously is not what I want to do but that causes this error to go away but not that one because here there's still a code path that gets me there without getting rid of the undefined so really the fix is more likely to say equal to zero up here in the in the definition of the variable and in fact I don't even need to have a type on it anymore I can just say equal to 0 and then we infer that and now we know that in all code paths were we're good with that so that was one of the issues now another issue here is this complaint that object is possibly undefined on my text parameter now text this declared here to be an optional parameter that's what this question mark indicates and optional parameters can be undefined if because that's what you get if if the parameter wasn't passed to you now I could fix the bug by saying oh no it shouldn't be undefined well or it shouldn't be optional but now I get an error down here it's saying you can't not pass text to me so but let's say I do want it to be optional now I have to somehow check whether I got a text passed now one naive way I could do that is I could say if text and surround this whole thing with a truth a check like that and that takes care of the problem in here but now something else happened up here functional acts ending return statement and return verses not include undefined so basically the type checker has concluded you could fall out the bottom and that would cost you to return undefined but you've said that you return a number and a number can't be undefined and so you got to do something about that so I could say here return 0 and then that error would go away now that's one way I could fix this I could also instead say do sort of the bailout style if not text return and then do the rest and now we're good except well not quite type undefined it's notice in there you must return something so you have to return 0 or something so you see it's getting pretty hard to cheat this type checker you know it's it's it's really looking over your shoulder here now of course probably the real way we want to fix this is to surround it here to say if texts do the for loop right ok there we go so that leaves one bug in in my code it says here that argument of type string or null array is not assignable to a string array well so we're trying to pass a null but we said that it was going to be an array of strings so I guess we either have to get rid of the null or we have to include it in the type up here which we could do now once we do that then another issue now pops up this optic is possibly null so now we got to go chase that one down and say if line and and line dot length nah blah blah blah now we're good so as you can tell here this this is much much deeper type checking than than you've seen previously right and this really does catch an awful lot of bugs in in in your code so I would definitely encourage you to use this new strict null checking mode if you're not if not using it already just for kicks let's look at here do a few more the effects of nulls and undefined here's here's some crazy functions like here's a function that takes a string or a string array or null or undefined and then some code here we say if s so we're checking if s is truthy and in here as expected we get a it's either a string or a string array we got rid up an all or undefined but what do you think the type is down here it's actually string or null or undefined because the string could have been empty and an empty string is false E and so we actually might have a string down here and the checker knows this though but when you're writing the code you probably forgot about that right I mean so so these are like the gotchas the javascript is full of gotchas but the beauty of type checkers is the type checkers don't care about screwy rules as long as you put them in it can check him and that's that's what it's what it's doing here's that here's another one right where if typeof s is object what do you what do you think we get here well we get string array or no what well because typeof null is object in JavaScript it's one of the mistakes that that they made that they then decided all typeof null really should be null then they tried to fix it then that broke a bunch of code well we can't do that so there it is tombstone forever you know like so so so therefore you know but we know that it could still be null in here if you have that kind of a check right and down here we know that null is gone here's another one if s double equals undefined well s could be no or undefined here because double equals against null or undefined checks for both of them but if it's triple equals now it's only undefined that could pass through here so all these crazy little rules have been encoded and the checker will just relentlessly point it out to you it's like it gets really irritating but but but but you know you want you want to know this okay so that's that's nulls the other I'd say cool feature that we did in in typescript 2.0 discriminated union types let me try to show you those here's a classic peep piece of object-oriented code with an abstract class shape and then we have a circle and a rectangle and a square and day they have a radius and width and height or size and there's a get area function that computes the size and then we make a circle compute the error so OOP 101 now a lot of people tell me yeah I heard about this typescript thing it sounds really cool but you know what I I write functional style code and now all this stuff I don't need I don't need loop you know it's like typescript is all OOP it's like turning JavaScript into c-sharp you're right no it's not at all and I want to show you a different way of writing code in in the same kind of code in a more functional style and I want to show you how types grave really plays very very well in that space so we're gonna get rid of the OOP here I'm gonna get rid of all these classes and instead what we're gonna put in is a declaration that looks like this where we say a shape is a thing that can look that can have three different layouts there's a kind property that's the discriminant and the kind says what kind of shape are you and you can see here you can either circles rectangles or squares and then if you're a circle you have a radius and if your rectangle you have a width and a height etcetera sader pretty pretty easy to read actually what enables this is a feature called literal types and this is a type here circle this is a type whose only value is the string literal circle so the only thing you could assign to kind for in here is either circle or rectangle or square now let me also try to show you a function then that computes the area now in an object-oriented solution I would have had a tight coupling between my code and my data you know I have code and data in the same place right and that's convenient in a because it allows me to think of one thing but it actually brings about some dissonance in a lot of cases like one case for example is persistence let's say I'm writing a drawing program here we're gonna save my shapes right well I just want to convert them to Jason but I can't convert classes to Jason because what about my code so now I got to have data transfer objects and I got to take my class instances and put them into Jason and then save that and then when I read it I got to take the Jason back and put it into classes and I have to have these mapping layers and stuff lots of stuff infrastructure right that that doesn't really add anything to the solution and the other thing is what if someone gave me this object hierarchy but it didn't have a get area function in it our method in it what do I now do I can't I can't modify this library so now I got a right I get area function but now it's sort of this coat smell of instance of checks and what if I forget one and blah blah blah and so so that doesn't work so well either right but in the functional style code and data have are much more separated than here I basically defined my data and I have to find the entire domain I have said shapes can either be one of these three and that's it I know in a closed-ended manner but what everything could be would OOP this is another problem is I don't there might be a fourth kind of shape that I haven't heard of that no one that someone derived another one right and what do I do in my persistence layer who's gonna check that I know how to save that one as well right and so so there are all these interesting problems that come up so here is what it looks like to do it in the functional style now I can just say shape is kind : and then let's say we want to have a circle with a radius and you'll see that we can actually give you statement completion in here we know everything and then get area just I'm just gonna pass a shape like that now one thing now that that's really cool is you'll note that my data here is ready to go under wire it's just data I could of Jason dot parse this data I could just save it store it you know so zero friction to to to save and in fact if think about what if you were writing a micro service right where you get you get messages in Jason that have a kind and a payload and then you go that's what I'm writing here right so so this is really a very very common pattern now notice what happens here when the type checker gets a hold of all this stuff here in here I'm saying switch shape kind let me hover over kind and you'll see that we note time could either be a circle or a rectangle or a square at this point because we've Union together your possible discriminants right now when I write a switch statement and I say case circle notice in here that shape has been narrowed down to that case and so we know exactly that a shape in here is a circle and therefore we can actually give your statement completion and show you well you're a circle and you have a radius and nothing else in here and so all of these features that that you know that you're accustomed to continue to work what's even more cool is that we sort of know what what happens let's say I fight I don't have rectangles covered and then let's look at what is the type of shape here and you'll see that well I handled circles of squares in the switch statement above so it's been narrowed down to rectangle down here right so the type checker actually follows all of your flow and understand what's going on now let me try to look at what happens now what if I handle all of the cases then shape gets narrowed down to a type called never the checker knows you're never gonna get here because you've handled all the cases now we can actually take advantage of that interesting fact and we could introduce a an assert function here called assert never it's a funny function it says here's a function that takes an object whose type should never occur and it's gonna throw an exception saying something went wrong now and now what I can do down here is I can say assert never of shape and get rid of that throw there now if now see what happens here is as long as everything is good we're going to have an ever here and that's gonna passed a check but what if we forget one I forgot about rectangles a checker comes right up and tells me hey you didn't handle rectangles now that's exhaustive nest ekang if you if some of you have done functional programming I mean this looks an awful lot like a DTS and pattern matching and exhaustive nest egg and all of these patterns that you use in camel or f-sharp or or what have you but it's all done in JavaScript and it's all done with no new syntax either this is a very cool way to program this is actually how the typescript compiler is written internally that's we don't have any classes at all in a compiler the type checker is one big function it's a very big function it's like xx I don't know 1250 some thousand lines or but and all of our syntax trees and whatever it's all declared in this manner and it's a cool way to work so and typescript really Grox it too so so I highly recommend you you look at that and don't think of it just as an OOP exercise that's another thing you can do but this truly is a hybrid language that allows you to do both ok the other thing I'm gonna try and show you now is types checking of JavaScript here's an empty directory I'm gonna npm install jQuery because I'm gonna write some jQuery I'm I'm a retro kind of a dude and then I'm gonna npm install lo - there we go and then I'm gonna fire up a shield studio code and I'm gonna add a main Jas there we go and now I'm good to go and I'm gonna type dollar dot and boom statement completion where did that come from um I'm in JavaScript here how do you know anything about dollar but it well we know what NPM modules you have installed we can go consult no doubt of our modules and then we can go to NPM and see if there are type definitions available for those modules and if there are we can suck them down an auto provision your IDE with the types that correspond to the modules that you're using even though you haven't said anything about typescript you're just programming in JavaScript all of a sudden we can give you this great experience based on all of that type information for example we also know about low - yes there's type information available for low - so now I can say under bar dot filter pass an array of numbers like that and now we can start flowing the type so in the callback here we know that X is gonna be a number and so we know what methods are available on number and so without you doing anything you actually get a lot of the benefits and this is what's cool about typescript being a superset of JavaScript is that javascript is just typescript with no type annotations but that doesn't mean the checker can't check it can check a lot and in fact as we thought about this we sort of realized that hey what if we had a type checking mode that was more of a conservative checking mode you know when we're checking typescript we're basically if we're unsure about something we're gonna whine and give you an error and make you fix it just so we can be absolutely certain that we've checked everything but what if we had a mode that was sort of the opposite where well if it could be true great but if we for sure know this is wrong why don't we let you know about it and the checker can do that and it can actually do a really great job of it particularly on modern JavaScript that's written with modules and classes because we can statically analyze the structure of that so so let me show you what that looks like in real life let me fire up on a project here called get up crawl up which is an open source project that that we just grabbed from github it seduced by internally by Microsoft open so it doesn't really matter what it is just a bunch of JavaScript and I'm just gonna open all the files here there we go and lo and behold what I've done here the only thing I did after getting this this cloning this repo is I added a config file where I turn on check J s and that basically tells the compiler hey give it a shot check that JavaScript and see what you can what you can find out and and we actually find out a lot of stuff now this I should also say this is a snap in time of a particular repo where the programmers later fix the bugs we actually we actually grabbed a copy about a month later for another demo and whoa what what happened two bugs are gone oh well they found the bugs themselves the hard way right but so we have to go back to that previous commit where the bugs were there so so that's what you're seeing here here we go first one is in here we're calling a method and it's saying then parameters don't match well let's say go to definition notice that statement completion works and well this thing takes no parameters and they're passing it an argument that doesn't make sense we should we should tell you something about that right so so we do so let's not pass an argument there here's another one same thing we're passing two arguments function takes one argument God knows what's gonna happen to the other but let's let's make it take another argument and there that that goes away here's here's something else that's sort of suspect we're newing up an error object and then we're starting to properties on to it but error objects don't have underbar types and URL bar but of course you might mean to do this so you'll note that we have a little light bulb there and if I if I pop up the suggestion it says oh just ignore this error message and notice how we put a little comment on the line above that says ignore errors on the next line and so you can sort of go through and just tell yeah okay that's fine I've looked a dab one I don't I don't mind that one we're good we're good there and they go away here's another one new requests on payload except if we go to request there is no payload in here but we could add a payload it's actually good practice to always initialize your properties in the constructor because the VM will do better layout that way and then that error goes away same thing here there simply isn't an event its method on so I don't know how this code could I've ever run well oh it's code in a callback I guess that callback never got called right so so I guess they don't have test coverage of this particular one so we'll just get rid of that here's another one it says there's no type property on request well one of these suggestions that we have here if I control dot is just go initialize one so we'll just simply have it add and now if I say go to definition you'll see this line of code that our code fix inserted so you can actually just ask for the fix if you will here's another one that's similar to that I'm just gonna say yep go initialize this in the constructor if we go to the constructor you see that we added another one I can keep going dude there's there's maybe one that I think is interesting here moment diff and it says there's no diff then I went and looked at the type declarations and know there is a diff but but it but it's on the result of calling moment not on you know so that one took me a little while to think through but this is the kind of stuff that that type checkers can find because because for a moment we actually could find the type declaration files for that by Auto provisioning and then checking against that and for all of the other stuff you saw in the classes it's because we can analyze the static layout so there's a whole bunch of cool stuff we can do even without you doing anything to your code but then of course since typescript is a superset you can ease into it and start writing type annotations and then we could do even better but we're really very focused on reducing that glideslope into into typescript and allowing you to stop and and actually just still have JavaScript all right let me go back and quickly hop through the last few slides type system I mean my point really is at the bottom you can look at a slides afterwards but it's this type system is both object or in ant functional and generic and gradual and structural and it's a very interesting type system it does a lot of stuff that I haven't seen any type systems do before it's a lot of fun to work on tooling you saw me use Visual Studio code of course you can use big visual studio but you can also use a variety of IDs out there we actually have great support for all of these IDs and the reason we do is that we've engineered typescript to be this service that you can use from your editor plugin so you don't have to understand anything you just have to tell us about all the edits that happen and then we can cough up all of the answers from this outer process node server that that we run that talks to your to your extension typescript adoption we are growing leaps and bounds we're up to more than four million downloads per month now on NPM we recently made it into the top 20 programming languages in red monks survey we're up there now as number 17 with Scala and Swift so it's it's it's great to see that the community is really picking up on on typescript at this point one that particularly made me happy is that we are now in the top three most loved programming languages on stackoverflow right behind thank you behind small talk and and rust one morning I had the other day I was reading my coffee and whoa look at this article here someone at the engineering group at at slack was writing about how they spent six months rewriting all of their JavaScript apps to typescript and they loved it and so so you know and lots of other companies are doing it and in fact a lot of the JavaScript frameworks are using typescript and honestly this is perhaps the most hortence lie because if anyone knows JavaScript and all of the issues and the JavaScript community it's the people writing the frameworks and look at how many of them are using typescript in their day to day development and that really warms my heart that's it pretty much for me here I encourage you to go visit typescript Lane org where which just got a revamp we have a whole bunch of new getting started guides that are really cool that allows you to see how you get started with angular react or view or what have you come talk to us on the issue tracker on github the whole team is there every day it's is where we live and we also have a booth downstairs come talk to us I'm gonna pop down there as much as I can but we have Daniel and Boden down there great guys to talk to about about typescript so that's it for me thanks sir thanks for coming and thanks for using our product thank you [Applause]
Info
Channel: Coding Tech
Views: 22,305
Rating: undefined out of 5
Keywords: javascript, typescript, typescript vs javascript, typescript tutorial, typescript 2, typescript advanced
Id: 0ChtcZmb3dI
Channel Id: undefined
Length: 60min 36sec (3636 seconds)
Published: Mon Nov 27 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.