Typescript for Noobies

Byron Murillo
7 min readMar 6, 2022

What is TypeScript?

The definition from the official website says: “a typed superset of JavaScript” but it assumes you know what a “superset” is and what “typed” means. TypeScript is a layer because you can write TypeScript code in your editor. After a compilation all that TypeScript stuff is gone and you’re left with plain, simple JavaScript.

If the idea of a compilation step confuses you keep in mind that JavaScript is already compiled and then interpreted. There is a JavaScript engine that reads and executes your code. But JavaScript engines are not able to read TypeScript code so any TypeScript file should go under a “pre-translation” process, called compilation.

What do I need to learn to use TypeScript?

TypeScript is essentially a JS linter. Or, JS with documentation that the compiler can understand.

Therefore, in contrast to other languages like CoffeeScript (which adds syntactic sugar) or PureScript (which does not look like JavaScript at all), you do not need to learn a lot to start writing TypeScript code.

Types in TS are optional-but it’s not recommended-, and every JS file is a valid TypeScript file. While the compiler will complain if you have type errors in your initial files, it does give you back a JavaScript file that works as it did before. Wherever you are, TypeScript will meet you there, and it is easy to build up your skills gradually.

Why TypeScript?

TypeScript has been increasing in its popularity for the last couple of years. Angular, one of the largest frontend frameworks, is using TypeScript. About 60% of JS programmers already use TypeScript, and 22% wish to try. Why?

Historically, JavaScript has ended up as the main language for scripting web pages and apps on the Internet. It is now possible to use JavaScript on both the frontend like React and Angular and the backend with frameworks like Node.js.

What are types, and how do they work in TS?

Brief intro to types

Types are a way to tell correct programs from incorrect before we run them by describing in our code how we plan to use our data. They can vary from simple types like Number and String to complex structures perfectly modeled for our problem domain.

Programming languages fall into two categories: statically typed or dynamically typed.

In languages with static typing, the type of the variable must be known at compile-time. If we declare a variable, it should be known (or inferrable) by the compiler if it will be a number, a string, or a boolean. Think Java.

In languages with dynamic typing, this is not necessarily so. The type of a variable is known only when running the program. Think Python.

TypeScript can support static typing, while JavaScript doesn’t.

Due to the static typing of TypeScript, you will need to try harder to:

  • introduce undefined variables (compile-time warnings help)
  • sum two strings that have numbers in them (like “4” + “20” = “420”)
  • do operations on things that don’t permit them, such as trimming a number.

With static type systems, you can create your own composite types. This enables engineers to express their intentions in more detail.

Explicit types also make your code self-documenting: they make sure that your variables and functions match what is intended and enable the computer to take care of remembering the surrounding context.

Main types of TypeScript

TypeScript has a variety of basic types, like Boolean, Number, String, Array, Tuple, etc. Some of these don’t exist in JS; you can learn more about them in the documentation of TypeScript.

In addition to those, here are some other types we want to feature to showcase the expressivity of TS:

Any

While any as a type can cover, it’s basically to save you from some not so necessary typing or interface, but it’s still not recommended.

Void

Void is used when there is no value returned, for example, as the return type of functions that return nothing.

TypeScript vs. JavaScript

It pays to be pragmatic. Have a look at this graph:

From nowhere, TypeScript is now in the 6th position in GitHub pull requests for Q2 2021, above PHP and C. (Source)

While a considerable cause of this is the support of TypeScript by companies like Microsoft (which created it) and Google, it is supported for a good reason.

3 reasons why you should choose TypeScript over JavaScript

1. TypeScript is more reliable

In contrast to JavaScript, TypeScript code is more reliable and easier to refactor. This enables developers to evade errors and do rewrites much easier.

Types invalidate most of the silly errors that can sneak into JavaScript codebases, and create a quick feedback loop to fix all the little mistakes when writing new code and refactoring.

2. TypeScript is more explicit

Making types explicit focuses our attention on how exactly our system is built, and how different parts of it interact with each other. In large-scale systems, it is important to be able to abstract away the rest of the system while keeping the context in mind. Types enable us to do that.

3. TypeScript and JavaScript are practically interchangeable, so why not?

Since JavaScript is a subset of TypeScript, you can use all JavaScript libraries and code that you want in your TypeScript code.

Most popular JavaScript libraries have types — Definitely Typed is a repository with types for a lot of different JavaScript libraries that you can use to make your interactions with them more type-safe.

This means that you can gradually adopt TypeScript in your JavaScript codebase, first adding types to individual modules and then expanding to… consume the known universe, I guess.

Drawbacks of TypeScript

You can’t just take a JavaScript team or a JavaScript repository and instantly switch them to idiomatic TypeScript. There are tradeoffs, and upfront time sacrifices you have to make.

While we can argue about the savings that being explicit about types give you in the long run, in the short run, it does take more time to add them. This is arguably not a huge deal, but it is an argument in favor of JavaScript.

Therefore, you might not choose TypeScript for small projects and prototypes for your own use.

To sum it up, here’s a quick comparison of TS and JS languages:

TypeScript quickstart guide

TypeScript compiler

To compile your TS code, you need to install tsc (short for TypeScript compiler). The easiest way to do it is through the terminal. This can be done easily via npm by using the following command:

npm install -g typescript

If you want to use TypeScript with Visual Studio Code, there is a handy guide on their website.

Once you have installed tsc, you can compile your files with tsc filename.ts.

Migrating your files from JavaScript to TypeScript

Let’s say that we want to change the following JavaScript file to TypeScript due to odd behavior:

function my_sum(a, b) {
return a + b;
}
let a = 4;
let b = "5";
my_sum(a, b);

Good news. Any JS file is technically a valid TypeScript file, so you’re up to a great start — just switch the file extension to .ts from .js.

TypeScript has type inference, which means that it can automatically infer some of the types you use without you adding them. In this case, it presumes that the function sums two variables of type any, which is true but of no great use right now.

If we want to sum only numbers, we can add a type signature to my_sum to make it accept only numbers.

function my_sum(a: number, b: number) {
return a + b;
}
let a = 4;
let b = "5";
my_sum(a, b);

Now, TypeScript provides us with an error.

Argument of type 'string' is not assignable to parameter of type 'number'.

Good thing we found where the error is. :) To further escape errors like these, you can also add type definitions to variables.

let b: number = "5" // Type '"5"' is not assignable to type 'number'.
let b: number = 5 // Everything ok.

TypeScript is quite flexible in what it can do and how it can help you. For a less trivial example on how to move your existing JavaScript codebase to TypeScript or use TypeScript to improve your JS code, read this guide.

How to use TypeScript in a browser?

To run TypeScript in a browser, it needs to be transpiled into JavaScript with the TypeScript compiler (tsc). In this case, tsc creates a new .js file based on the .ts code, which you can use any way you could use a JavaScript file.

Resources for further learning

If you want to learn more about TypeScript, here are a few other resources that you can check out:

  • TypeScript Documentation. The official documentation features great guides for beginner TypeScripters, including guides for those switching from other programming languages.
  • TypeScript Deep Dive. This free web resource has everything you need to start off with TypeScript, including more detailed explanations of the sections we’ve already covered here.
  • Programming TypeScript: Making Your JavaScript Applications Scale. This is a great book for those of you already fluent in JavaScript. It will help you get up and running with writing TypeScript in no time.

Conclusions

Overall, TypeScript is a great tool to have in your toolset even if you don’t use it to its full capacity. It’s easy to start small and grow slowly, learning and adding new features as you go. TypeScript is pragmatic and welcoming to beginners, so there is no need to be afraid.

--

--