TypeScript - The Basics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
I can pretty easily say that the one tool that's had the biggest impact on my productivity as a web developer is typescript and that's pretty amazing considering a few years ago I had no interest in learning it and was only exposed to it because I had a client that required an angular app in today's video I'm gonna show you all the basic concepts needed to be successful with typescript and I'll throw in a few pro tips here and there that I find especially useful if you're new here like and subscribe and there will be a t-shirt giveaway with this video all you have to do is leave a comment below and we'll pick a random winner next week I want to start with a shout-out to basarat Syed who is the author of the typescript deep dive book it's my go-to resource for advanced concepts and it's free and open source so originally I was resistant to even learn typescript because I wasn't super comfortable with strong typed languages and I really tried to avoid writing any more code than I have to but this is the situation where writing a little more code upfront will pay big dividends as your project grows the biggest benefit is actually just tooling what you get in your IDE like vs code when you use type annotations or work with libraries that are strong typed your code will be automatically documented in the IDE so you really have to refer back to online documentation for the libraries that you use in addition that compiler can catch bugs in advance which is a far more efficient way to refactor code I think this reddit post says it best would you rather have silly errors during development or insanity inducing errors in production another cool benefit of typescript is that there's virtually no learning curve if you know JavaScript that's because it's a superset of JavaScript so any valid jsk is also valid in typescript so you can learn it incrementally as you go and it also allows us to write our code with future JavaScript features without having to worry about whether or not this code will be supported in our environment because we can transpile it to multiple JavaScript flavors now that you know typescript is awesome let's go ahead and get started the first thing you want to do is install typescript globally with NPM doing this will give you access to the TSC command which will run the typescript compiler at the time of this video I'm running version 3.1 so the first thing we'll do is create an indexed ES file and typescript code on its own can't run anywhere it won't work in the browser or an ojs or anything like that what we do is use the typescript compiler to convert that typescript code to vanilla JavaScript let's start by writing some plain JavaScript in our typescript file and then compile it so we'll just say console.log hello world then we'll go down here to the command line and run TS c index TS you'll notice that creates an index j s file that's our actual JavaScript code that we can run in the browser or node and because we just wrote plain JavaScript that code is identical to what's in the index TS file by default typescript will compile to es 3 which doesn't have support for async await so let's see what happens when we write an async function in our TS C file and then compile it so you'll notice here that our code gets transpiled to this crazy-looking javascript just so we can use async await in our main typescript code the compiler is actually very sophisticated and there's a ton of different options that you can pass to it to customize its behavior you could pass these options and from the command line but the standard way to do it is to create a TS config JSON which will automatically get picked up when you run TS c the TS config can seem pretty overwhelming at first but there is usually only a few options that you have to think about for the most part the first one is the target and this is the flavor of javascript that your code will be compiled to so if we set our target to es next and then run TS c you'll see that it compiles our code with async/await natively because it's targeting the latest version of javascript which supports that syntax another option that we'll want to set right away is watch true which will just recompile our code every time we save the file that'll just save us from rerunning that TS c command after every change the next option will look at is Lib which allows us to automatically include typings for certain environments such as the Dom or ES 2017 so if you're building a web application you'd want to include that Dom library which allows typescript to compile your code with all the native Dom classes without any compilation errors for example if we go back to our code we can use the URL class which is part of the Dom and we'll get autocomplete and intellisense on this class so this is where the incredible tone of typescript starts to come in if we hover over the class we have integrated documentation as well as an error message telling us exactly why this code won't run and if we want a really explicit view of the interface we can right click and go to the Taipings then we'll have a view of every property and method that exists on this class but usually that's not necessary because the stuff will just autocomplete for you as you start typing the next thing we'll look at is the use of third-party libraries so let's go ahead and install lodash with NPM and you'll see that creates a node modules folder with the source code for lodash a lot of mainstream libraries like firebase for example ship with type declarations automatically but load a shiaa is not one of them so if we go into our index TS and import lodash we'll get a warning from typescript saying that there are no declarations found which means we're not going to get any auto complete or intellisense in the IDE but the good news is there's a giant mono repo out there with community maintain types if we go ahead and install the types in our development environment will have autocomplete and intellisense for every lodash function so now that we know how the typescript compiler works let's go ahead and write some code that uses type annotations there are two ways you can strong type your code implicitly or explicitly so let's say we have a variable that should be a number if we assign a value to this variable when it's declared its type will automatically be inferred as you can see here it's a primitive number type then if we go down here and try to assign a string value to this variable it's going to give us an error because a string is not assignable to a number if this code were vanilla JavaScript we wouldn't catch this bug until we actually run our code somewhere but with typescript we know about it right away unlike languages like C sharp or Java we can actually opt out of the type system by annotating our variable with any this just means that this variable can be assigned any value and the compiler won't type check it ideally you want to avoid doing things like this when possible but it does give typescript a ton of flexibility in the last example we gave our variable an implicit number type but what if we don't have a value to assigned to it upfront if we don't add any type annotations to it it's going to be inferred as an any type so we can assign both a string and a number to it if we want to annotate it with a type we can just do colon followed by number which is one of the built-in primitive types in JavaScript when we do that we get an error under the string value because we can't assign it as that type one tip that I'll give you here is that if you have an implicit type don't bother explicitly strong type in it for example here we're assigning a value that's a number so adding the number annotation is really just redundant so we've looked at some of the built-in types in JavaScript but you and also create your own types from scratch first you'll give the type a name which is typically in Pascal case and for right now we'll just go ahead and arbitrarily assign our style type to a string then we can declare a variable that's annotated with this style type and then we'll get feedback for this custom type instead of just a regular string right now this is super redundant but let's say our style type can only be bold or italic we can create a union type by separating them with a pipe and now we can only assign this variable to these two specific values and we're not limited to just strings we could even extend this custom type with a number so that's pretty cool but more often than not you'll be strong typing objects that have multiple properties with multiple different types let's imagine we have two objects and we want to enforce that this object shape has a first and last name with string types composing objects or class instances that don't have the correct shape is an easy way to create bugs in your program but with typescript we can enforce the shape of an object with an interface if we know that the shape of the person object walls be the same then we can define an interface that defines the types on each property now we can use this interface to strong type these objects directly or we could use it as the return value from a function or as an argument or anywhere else in our code now sometimes an interface like this can be a little too restrictive but you can actually maintain the required properties and then add any additional properties to be added by creating a key with a type of string with a value type of any so now a first and last name will be required but you can also add any additional property that you want to this object now let's go ahead and switch gears to functions strong typing a function can be a little more complex because you have types for the arguments and also the return value so here we just have a plain JavaScript function without any types that raises X to the power of Y so currently we could add string values as the arguments here and we wouldn't get any air from the compiler but obviously this function is going to fail if we try to pass it any non-number value you can annotate arguments the same way we do with variables by just adding a colon and then the type after it and that will ensure that only numbers can be passed to this function so the function implicitly has a number return value because we're using the native math javascript library but we can annotate a specific return value ty after the parentheses and before the brackets so if we set that type to a string you'll see it's underlined in red because it's returning a number to implement this function correctly we can call to string which will then clear out that underlined error and in many cases you might have functions that don't return a value or create some kind of side effect in that case you can type your function return value to void so you'll commonly see the void type on functions like event listeners or side-effects that just don't return a value the next thing we'll look at is how to strong type an array so we'll start by creating an empty array and then pushing a few different values to it with different types we can force this array to only have number types by doing a number type followed by bracket signifying that it's an array now you can see we get an error every time we try to push a value that's not a number this is especially useful when you're working with an array of objects and you want to get some intellisense as you're iterating over those objects for example if we retrieved an array of people from our database we could use our person interface to know the exact shape of those objects as they're retrieved typescript also opens the door to a new data structure called a tuple these are found in other programming languages like Python and basically they're just a fixed length array where each item in that array has its own type so we can name our type my list and then we'll give each of its values a different type currently this is giving us an error because we're initializing this array as an empty array but the compiler is expecting all these values to be defined up front so one thing you can do is make these values optional by putting a question mark after the type and you can also use this question mark syntax and other places in typescript for example to make function arguments optional the last thing I want to show you is typescript generics you may run into situations where you want to use a type internally inside of a class or function a good example is an rxjs observable which itself is just a class that has an internal value that you can observe so the capital T in this code represents a variable type that we can pass in to strong type this observables internal value so this allows us to specify the internal type at some later point in our code for example we might have an observable of a number or maybe we have an observable of our person interface and we can also do this implicitly if we create a new observable of a number it's going to implicit we have that internal number type so more often than not you'll be using generics rather than creating them but it's definitely an important thing to know I'm gonna go ahead and wrap things up there hopefully this video gave you an idea of why typescript is so powerful but we really only scratched the surface here I'd like to do a video on object oriented versus functional programming and typescript or possibly decorators so let me know what you want to see next in the comments if this video helped you please like and subscribe and if you want to learn more consider becoming a pro member at angular firebase comm you'll get unlimited access to my following courses as well as project support on slack and of course I will mail you this laptop sticker that you see on the screen now thanks for watching and I will talk to you soon
Info
Channel: Fireship
Views: 847,775
Rating: 4.9509482 out of 5
Keywords: angular, webdev, app development, typescript, javascript, lesson, tutorial, js, ts, typescript vs javascript, strong type, typescript tutorial, ts tutorial, type script, esnext, ecmascript
Id: ahCwqrYpIuM
Channel Id: undefined
Length: 12min 1sec (721 seconds)
Published: Thu Nov 29 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.