Welcome back to my blog. Today, I’m going to talk about Typescript, what this programming language solves, how Typescript helps you improving your JS code and its main features.
- Reference variables that do not exist
- Work with objects of an unknown “shape”
- Code is interpreted by a browser, but if our code is broken, you won't catch it until runtime, when the browser throws an error.
Typescript prevents errors like the ones above to happen, by extending JS with types.
- This means that when we write a .ts file, you can write plain JS with all of its extra features being completely optional.
- For example, our IDE will provide feedback when using a variable that doesn’t exist.
- That would allow us to fix code as we go, with instant feedback.
Typescript behaves like a compiled language, where JS is the compilation target.
We can run the typescript compiler using the tsc command, followed by the name of the file:
>> tsc index.ts
- You can choose any “flavor” of JS you want if you need to target ancient browsers.
- You can use the latest and greatest syntax features of JS without having to worry if they will be supported in an older environment.
Typescript projects normally have a ts config file which provides an infinite number of ways to customize the behavior of the compiler.
The main goal of Typescript is to enable static typing:
- A way to achieve this is that it allows us to annotate our code with types.
- We can strongly type a variable using a colon followed by its type, like string, boolean, or number.
- That is known as an explicit type.
If we then try to assign a value of a different type to a variable strongly typed, we would get an error.
Alternatively, if we set an initial value it will implicitly infer the type. There may be cases where you want to opt-out of this behavior. For that purpose, you can annotate with the “any” type. Example:
let appName: any = 'appname'
Another important thing is that when working with an array we use brackets to strongly type a list.
In addition, you can define your own custom types and interfaces. This would be especially useful when working with objects.
In a Typescript interface, we can define various types of properties on an object, and then, we can apply that interface to a plain JS object.
The benefit of strongly typed code is that we get autocompletion everywhere in the IDE. This way, we don’t have to jump back and forth to documentation.
Finally, during this week I had the opportunity to refresh my JS knowledge along with my knowledge of technologies such as NextJS, React, NestJS, and Node. Moreover, I also worked with tools such as DBeaver to manage and administrate a local database and learned more about Docker and the use of containers to allow us to contain our databases. At the same time, I got familiarized with the use of Bitbucket as a version control tool and collaborative work.
That’s it for this post, have a great week, and see you soon!