YTread Logo
YTread Logo

TypeScript - The Basics

May 08, 2024
I can pretty easily say that the tool that has had the biggest impact on my productivity as a web developer is typing and that's pretty surprising considering that a few years ago I had no interest in learning it and was only exposed to it because I had a client. which required an angular application in today's video. I'll show you all the

basics

needed to be successful with typing and add a few pro tips here and there that I find especially helpful if you're new here. Subscribe and there will be a drawing for a t-shirt with this video.
typescript   the basics
All you have to do is leave a comment below and we'll pick a winner at random next week. I want to start with a shout out to basarat Syed, author of The Deep Dive Book on Typing is my go-to resource for advanced concepts and it's free and open source, which is why I was originally reluctant to even learn typing because I wasn't very comfortable with strongly typed languages ​​and I really tried to avoid writing 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.
typescript   the basics

More Interesting Facts About,

typescript the basics...

The biggest benefit is actually just using tools that you get in your IDE, as compared to the code when you use type annotations or work with libraries that If you are strongly typed, your code will be automatically documented in the IDE, so it really You'll need to check the online documentation for the libraries you use, plus the compiler can catch errors early, which is a much more efficient way to refactor code. I think this Reddit post says that you'd rather have silly bugs during development or madness-inducing bugs in production. Another interesting benefit of

typescript

is that there is practically no learning curve if you know JavaScript, because it is 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 write our code with future JavaScript features without having to worry about whether or not this code will be compatible in our environment because we can transpile it to multiple versions of JavaScript Now that you know that Typescript is awesome, let's go ahead and get started.
typescript   the basics
The first thing you should do is install Typescript globally with NPM. This will give you access to the TSC command that the Typescript compiler will run at the time of this video. version 3.1, so the first thing we're going to do is create an indexed ES file and the typed code alone can't run anywhere, it won't work in the browser or in an ojs or anything like that. What we do is use the typescript compiler. To convert that typescript code to basic JavaScript, let's start by writing some simple 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.
typescript   the basics
TS you'll notice that it creates an index j s file which is our actual JavaScript code that we can run in the browser or node and because we just wrote simple JavaScript, that code is identical to what's in the TS index file by default, the typescript will compile to es. 3 which has no 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 notice here that our code is transpiled into this crazy looking javascript just so you can use async await in our main typescript code.
The compiler is actually very sophisticated and there are a lot of different options you can pass to it to customize its behavior. You can pass these options and from the command line, but the standard way to do this is to create a TS configuration JSON that will be automatically selected when you run TS c TS configuration can seem quite overwhelming at first, but there are usually only a few few options you need to think about for the most part, the first is the target and this is the type of javascript that your code will be compiled into, so if we set our target to is next and then run TS c you will see that compiles our code with async/await natively because it targets the latest version of javascript. that supports that syntax, another option we'll want to set right away is see true, which will simply recompile our code every time we save the file, saving us from re-running that TS c command after each change, the following option will appear. at is Lib, which allows us to automatically include scripts for certain environments, like Dom or ES 2017, so if you're building a web application, you'll want to include that Dom library that allows Typescript to compile your code against all native Doms. classes without compilation errors, for example, if we go back to our code, we can use the URL class which is part of Dom and we will get autocomplete and intellisense in this class, so this is where the awesome typescript tone starts to appear. if we hover over the class we have built in documentation as well as an error message telling us exactly why this code is not running and if we want a really explicit view of the interface we can right click and go to Taipings and then have a view of every property and method that exists in this class, but usually that's not necessary because things will just auto-complete when you start typing.
The next thing we'll look at is using third-party libraries, so let's move on. and install lodash with NPM and you will see that it creates a node modules folder with the lodash source code. Many mainstream libraries like firebase for example ship with type declarations automatically, but loading a shiaa is not one of them, so if we go into our TS index and import lodash we will get a typescript warning saying no declarations found , which means we won't get any autocompletion or intellisense in the IDE, but the good news is that there is a giant mono repository out there.
With community maintained types, if we go ahead and install the types in our development environment, we 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 code that uses typescript annotations. guy. There are two ways. you can write your code implicitly or explicitly, so let's say we have a variable which should be a number, if we assign a value to this variable when it is declared, its type will be inferred automatically, as you can see here it is a number type primitive, so if we go down here and try to assign a string value to this variable, it will give us an error because a string cannot be assigned to a number.
If this code was basic JavaScript, we wouldn't catch this error until we actually ran our code somewhere. but with typescript we know right away, unlike languages ​​like C Sharp or Java, we can 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 will not write the check. You should ideally avoid doing things like this when possible, but it gives a lot of flexibility to typing. In the last example, we gave our variable an implicit number type, but what if we don't have a value to assign to it in advance? don't add any type annotations to it, it will be inferred as any type, so we can assign it a string and a number.
If we want to write it down with a type, we can only make two points followed by a number, which is one. of the primitive types built into JavaScript, when we do that, we get an error below the string value because we can't assign it as that type. One tip I'll give you here is that if you have an implicit type, don't do it. Don't bother writing explicitly for sure, for example, here we are assigning a value that is a number, so adding the numeric annotation is really redundant, which is why we have looked at some of the built-in types in JavaScript, but you can too create your own. types from scratch will first give the type a name which is normally in the Pascal case and for now we will just go ahead and arbitrarily assign our style type to a string, then we can declare a variable that is annotated with this style type and then we will receive comments for this custom type instead of just a normal 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 just assign this variable to these two specific values ​​and we are not limited to just strings, we could even extend this custom type with a number, so that's great, but most of the time you will be strong when writing objects that have multiple properties with multiple different types let's imagine we have two objects and we want to enforce that the shape of this object has a first and last name with string types that make up objects or class instances that do not have the correct shape is an easy way to create errors 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 walls of the person object is the same, then we can define an interface that defines the types on each property, now we can use this interface to safely write these objects directly or we could use it as a return value of a function or as an argument or anywhere else in our code.
Now sometimes an interface like this can be too restrictive, but you can actually maintain the required properties and then add additional properties. will be added by creating a key with a string type with any value type, so now a first and last name will be required, but you can also add any additional properties you want to this object. Now let's go ahead and shift gears. functions writing a force function can be a little more complex because it has types for the arguments and also the return value, so here we just have a simple JavaScript function without any types that raises X to the power of Y, so which currently we can add string values. like the arguments here and we wouldn't get any air from the compiler, but obviously this function will fail if we try to pass it any value other than a number, you can annotate the arguments the same way we do with variables by just adding a colon. and then the type that follows and that will ensure that only numbers can be passed to this function, so the function implicitly has a numeric return value because we are using the native math javascript library, but we can annotate a specific return value ty after of the parentheses. and before the square brackets, if we set that type to a string, you will see that it is underlined in red because it returns a number to implement this function correctly, we can call the string, which will then clear that underlined error and in many cases, could If you have functions that don't return a value or create some kind of side effect, in that case you can write the return value of your function to void, so you'll commonly see the void type in functions like event listeners or side effects that simply don't they do it.
To return a value, the next thing we will look at is how to force write an array, so we will start by creating an empty array and then by inserting some different values ​​with different types, we can force this array to only have one number. type by typing a number followed by a square bracket, which means it is an array. Now you can see that we get an error every time we try to enter a value that is not a number. This is especially useful when you are working with an array of objects and want to get some clever sense while iterating over those objects, for example if we retrieve a series of people from our database we could use our person interface to find out the exact shape of those objects as they are recovered.
Typescript also opens the door to a new data structure called a tuple, which are found in other programming languages ​​like Python and are basically just a fixed length array where each element of that array has its own type, so we can name our type as my list and then we will give it each of its values ​​is of a different type currently, this is giving us an error because we are initializing this array as an empty array, but the compiler expects all these values ​​to be defined in advance, 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 are optional.
The last thing I want to show you is typescript generics, you may come across situations where you want to use a typescript internally within 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 Tcapital letter in this code represents a type of variable that we can pass to the strong type. internal value of the observables, so this allows us to specify the internal type at some later point in our code, for example we could 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 is going to imply that we have that type of number internally, so most of the time you will use generics instead of creating them, but it is definitely important to know.
Hopefully, I'll move on and finish things there. This video gave you an idea of ​​why typing is so powerful, but we've really only scratched the surface here. I'd like to make a video on object-oriented programming versus functional programming and typescript or possibly decorators, so let me know what you want to see next. the comments, if this video helped you, please like and subscribe, and if you want to learn more, consider becoming a pro member of angular firebase comm. You'll get unlimited access to my next courses, as well as support for slack projects, and of course, I'll send you an email.
You have this laptop sticker that you see on the screen now, thanks for looking and I'll talk to you soon.

If you have any copyright issue, please Contact