Why We Choose Typescript All the Way Through

Written by: Matias Hernandez

What can be a significant improvement for your JavaScript developer team?

What can take them to the next level of confidence and productivity? Typescript can be that kind of addition that can leverage a world of new improvements in the developer experience, but it comes with a bit of a learning curve.

In this article, I will run you through some resources about Typescript, how this can give your team more confidence and increase productivity, and some examples about using Typescript with React.

Let's check some data about Typescript. In the results published in the report "State of Frontend 2020," there was a question, "Have you used Typescript during the last year," and an overwhelming 77% answered, Yes (45,000 developers responded).

Another great metric is the result of the question "Do you like Typescript better than Javascript?" where 54% said that they prefer Typescript the most.

There is another source of metric that you can check, the famous State of JS, where you can see that Typescript usage grows from 66% in 2019 to a gigantic 78% in 2020! Similar metrics for the Satisfaction question.

So, it’s easy to notice that Typescript is a big player in the web development world, but what is all this buzz about? What is Typescript?

Typescript is a compiled language, which can be described as "JavaScript for application-scale development." Typescript (TS) is a strongly typed language designed by Microsoft as a superset of JavaScript. TS delivers a language and a set of tools. What does that even mean? Typescript is just JavaScript but with static typing. But Typescript can't be executed in the browser. Browsers only know how to parse and execute JavaScript code; for this reason, typescript ships with a compiler (tsc) that reads your TS code, performs a type checking, and if all went okay, an output performant JavaScript code.

So, what does Typescript code look like? (extracted examples of codebases below). As you can see, it can be more verbose than plain old JavaScript with all of the type definitions but at the same time it's kind of similar to what we were used to writing, right?

What can Typescript do for me and my team?

In any software project, we will have bugs, they are unavoidable. Still, we all strive to find ways to minimize that number or catch them before reaching the production environment and affecting the users. These errors can be in many forms; some can just be typos or genuine implementation issues or nuances from the programming language itself. JavaScript is a flexible, dynamic language where you can do whatever you want without any restriction. For example, you can mutate any variable, pass any data type to every function, etc. This can be seen as a powerful feature since the barrier to write JavaScript code is really low. Still, if you are crafting big applications with complex logic, JavaScript will cause self-inflicted errors by itself; no matter how experienced your team is, errors will come. One way to avoid these errors is by testing your code: unit test, integration, and e2e test will create some degree of confidence and help you to avoid bugs in the first place and not ship them bugs to production.

  • Typescript is a Test Typescript can be considered part of what is known as "statical analysis tools," which means that typescript processes verify your code without actually running, checking the data flow based on the types. Typescript compiler will parse your code, create an AST and then traverse the pieces to check how they communicate with each other. This process can be considered some type of test. The process checks your code to avoid bugs and avoid even committing to the main branch. A very constrained example is: Imagine you have a function that calculates your company's earnings, you expect that this function accepts numbers, right? But what happens if some unknown bug creates string data and passes that as an argument to your function? It will break, and you wouldn’t even notice until the tests are run or manually tested, or worse until it hits production. How could Typescript save you here?

Typescript will SCREAM to you that the arguments you are passing are strings and can't be used by your wonderful function by just giving the type of the expected data. And this will happen while you are writing the code! So using Typescript is like running a never-ending test that oversees what you write in order to ship clean code and not ship low-quality code.

  • Confidence What do you gain when running tests on your code? Confidence. Confidence that your code does what it is supposed to do. Since Typescript is "testing" (or checking) your data flow, you can focus on designing the correct solution for your problem and be sure that the algorithm that you crafted will do what it is supposed to do without fiddling with checking the valid arguments or that the correct data is returned. This confidence will lead to a better maintenance and improvement experience. Since Typescript will check the data types, you can rely on the type system for big refactors without errors (only the ones related to the business logic). The use of types will invalidate almost every "silly error" that can sneak into Javascript codebases (undefined is not a function, sound familiar? )
  • Better coding experience Another win of Typescript for developing a "Javascript" application is the significant improvement in developer experience (well, there are a few trade-offs that we will describe later in the article). As a developer, you spend most of your time sitting in front of your screen staring at your code editor. The idea of using a code editor is to make your life easier and be more productive by leveraging some tasks to the dev environment. Some of these tasks are related to the language itself, and as was mentioned before, Typescript allows static code analysis tools to run. This tooling around Typescript offers immense features for your "developer experience," like:
  • Code auto-completion Most code editors will auto-complete what you are typing, allowing you to write faster and confidently, but if we are talking about javascript, this auto-completion will be just some pieces of the language and maybe, a list of some of the current files used keywords like variables names and other. But with Typescript, since it is a static type language, the code auto-completion goes one level up, showing you documentation of every piece of code you write.
  • Real-time type checking Most IDE and code editors will run a type-check in the background reviewing the code you write and marking the type errors even before you save or run the code. This will help you to debug your code and be more confident about what was written.
  • Better refactoring experience Refactor is one of those tasks that, as a developer, you expect to come, but you kind of hate it because of the lack of confidence that you get when updating code with vanilla javascript. But again, since Typescript allows static analysis, the code editor can easily rename variables or functions, move files and the related imports, etc., helping a lot in the process. Also, if the algorithm you wrote didn't change the logic, you can be confident that the code works since Typescript will show you if some data type (and, therefore, data flow) is incorrect.
  • Better project quality Most software projects involve more than one developer, and the coordination between this team in terms of coding styles and good practices can be cumbersome. Still, by leveraging the power of Typescript, most of these tasks can be forgotten. The project maintenance and code quality can be trusted to the type analysis allowing the project to grow to keep the risk low. Another big win in this area is that types can be seen as code self-documentation. Not every developer is good at commenting on the code, and using JSDoc (that is actually good) is not always a reality for most teams. Typescript types help in this case by "documenting" the expected arguments and output of a function or method, describing the shape of an object, helping to keep some sanity and a clear mind when working with unknown code. Choosing typescript forces and helps developers have a data-driven mindset; this means that the implemented solutions often start by describing the data types that will be used (input and output) and then the corresponding algorithm to perform that data transformation. This approach will help spot and solve problems much earlier than vanilla javascript.
  • Typescript PitFalls Like everything in life, "Not all that glitters is gold," and there are some pitfalls where maybe the biggest one is a stuttering learning curve. Most Typescript developers started as JavaScript developers, and switching from the full dynamism of vanilla JavaScript to the strictness of (strict) Typescript can be difficult. When starting the project, you can think that you are writing more code than the one required before, or feel that the types are in your way of being productive, or even be surprised or scare by the TS errors, but trust me, it gets easier. There are many nuances in Typescript, and that can be a step to learn. There are different techniques to define data structures, and some of them can become complex quickly, but it will pay off in the end. Another pitfall is that Typescript allows you to slowly and increasingly add types to your project; this can be good when you are starting, but this feature can come back to bite you. This lack of strictness allows you just to make mistakes, use wrong type definitions, or simply not defining types for particular pieces of the code. If you are doing this with your code, you can work around this lack of confidence by knowing what you are doing and using a good test suite, but what happens when using a third-party code? You can get wrong types or lack of it from external sources, which will end in Typescript not being 100% reliable. But, don’t worry. Most popular open-source libraries are fully typed and have a strong community keeping an eye on the types; you can always check the source code or the source of the types code to be sure.

Some rules of thumb

But typescript has good things, right? And to get most of it, we should keep some sort of standard way of doing things, so here are some typescript good practices or rules of thumb for your project.

  1. Use strict mode from the get-go. Typescript enables you to add types to your codebase progressively. Still, even though this is a solid point to help you with the transition, you should strive to use the full potential of typescript when you are working in a production environment. To get this power, you need to enable strict mode in your typescript configuration. This forces you to explicitly type everything and, in consequence, will improve your documentation and confidence in the code.
  2. Don’t use a non-null assertion operator. This post-fix operator allows you to assert that a specific operator cannot be null nor undefined during runtime. Unfortunately, this means that by using it, you deliberately ignore an expression’s possible null value on a case-by-case basis. The issue with this operator is that you break the type checking by using it, and it is your responsibility to take the risk of ignoring the null value; therefore, this operator is wholly removed from the compiled javascript code.
  3. Use objects as functions arguments. Sometimes you have multiple arguments in your function, and type each of those arguments can be painful, so instead of separate input variables, you can use an object as a payload and kind the entire object.
  4. Choose unknown over anything else. Sometimes you have to look for a more straightforward type, don’t fall into the temptation to use any as type; this breaks the type checking, so, prefer to use unknown instead, this type will force you to at least check the type before using the value.

Join
Cleverdevelopers

Want to peek into our daily work? Our coaches recount real world situations shared as learning opportunities to build soft skills. We share frameworks, podcasts and thinking tools for sr software developers.

Keep on reading

Go to Blog home

The (remote) opportunities

We expect professionalism and client service, so we can offer a deeply caring experience for our clients. In return, you get freedom to work wherever you want. No timesheets, no big brother watching every move. We trust you to know what’s best to find the right solution.

    Don't see what you're looking for? Use our general application form

    Turn your toughest challenges into tangible business impact

    Get in touch

    Join Cleverdevelopers

    Want to peek into our daily work? Our coaches recount real world situations shared as learning opportunities to build soft skills. We share frameworks, podcasts and thinking tools for sr software developers.