DEV Community

Cover image for TypeScript Tutorial For Beginners: The Missing Guide - Part 1
Valentino Gagliardi
Valentino Gagliardi

Posted on • Edited on • Originally published at valentinog.com

TypeScript Tutorial For Beginners: The Missing Guide - Part 1

Just crossed 5k follower on dev.to! Thank you everyone! What a fantastic community! Who's on Twitter too? Let's connect => I'm here.

What is TypeScript and why you may want to use it? Learn more with this TypeScript tutorial for beginners and start adding types to your JavaScript code!

Originally published on valentinog.com/blog

In this episode:

  • what is TypeScript and why it exists?
  • first steps with TypeScript
  • sneak peak into TypeScript types

TypeScript tutorial for beginners: who this guide is for

The following guide is a TypeScript tutorial for JavaScript developers interested in learning more about TypeScript. That means a decent knowledge of "vanilla" JavaScript is appreciated, even though I'll give you pointers to the fundamentals as we go.

If you want to refresh your JavaScript skills before or after taking this tutorial check out my "Little JavaScript Book", available for free on Github and as a PDF/ePub/Mobi.

Do the words TypeScript and "beginners" belong in the same tutorial? I was not sure before writing this guide but every day I see a lot of beginners interested in TypeScript. If you decide to do so, be aware that learning TypeScript in your early days side by side with JavaScript will be hard. But it'll pay off in the long run. Keep going! If that's your case you're welcome to continue reading.

Before starting off make sure to have one of the latest version of Node.js installed on your system.

And now enjoy the reading!

TypeScript tutorial for beginners: 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. Instead to keep things simple you can think of TypeScript as of "a layer on top" of JavaScript.

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. Only after the first compilation step you're left with pure JavaScript code, ready to run in a browser. You'll see later how the TypeScript compilation is done.

For now let's keep in mind that TypeScript is a special kind of JavaScript but it needs a "translator" before running in a browser.

TypeScript tutorial for beginners: why TypeScript?

At first you won't understand exactly why TypeScript makes sense, after all it gets stripped down before becoming JavaScript code. "What's the point of TypeScript" you'll ask. That's a good question my friend.

In reality you'll see its benefits as soon as it will catch serious and silly mistakes in your code. More important your codebase will become well structured and almost self-documenting. You'll also appreciate improved autocompletion in your editor but that's just a nice side effect.

Anyway, every now and then a new thread pops up on Twitter or on the "orange website" saying that TypeScript is useless (the TypeScript tax) or too awkward. For example:

As with almost everything in IT there are partisans on both sides of the barricade. There are detractors and proponents for TypeScript but what matters is that TypeScript is a solid tool and having it in your tool belt won't make harm.

My goal here is to show the tool and help you forming your own idea on TypeScript.

TypeScript tutorial for beginners: setting up TypeScript

Setting up? Why so? Isn't TypeScript just a language? Kind of. TypeScript has also a binary which compiles TypeScript code to JavaScript code. Remember, browsers do not understand TypeScript. Let's install the binary then. Create a new Node project inside a new folder:

mkdir typescript-tutorial && cd $_
npm init -y
Enter fullscreen mode Exit fullscreen mode

and then install TypeScript with:

npm i typescript --save-dev
Enter fullscreen mode Exit fullscreen mode

Next up configure a Node script so we can run the TypeScript compiler easily:

  "scripts": {
    "tsc": "tsc"
  },
Enter fullscreen mode Exit fullscreen mode

tsc stands for TypeScript compiler and whenever the compiler runs it will look for a file named tsconfig.json in the project folder. Let's generate a configuration file for TypeScript with:

npm run tsc -- --init
Enter fullscreen mode Exit fullscreen mode

If everything goes well you'll get "message TS6071: Successfully created a tsconfig.json file." and you'll see the new file in the project folder. Now, keep calm. tsconfig.json is a scary configuration file. You don't need to know every single gist of it. In the next section you'll see just the relevant bits for getting started.

TypeScript tutorial for beginners: configuring the TypeScript compiler

It's a good idea to initialize a git repo and commit the original tsconfig.json before touching the file. We'll leave just some of the configuration options, removing everything else. Later you may want to compare your version with the original. For starting off open up tsconfig.json and replace all the original content with the following:

{
  "compilerOptions": {
    "target": "es5",
    "strict": true
  }
}
Enter fullscreen mode Exit fullscreen mode

Save and close the file. First of all you may wonder what tsconfig.json is for. This configuration file is read by the TypeScript compiler and by any code editor with TypeScript support.

TypeScript compiles down to "vanilla" JavaScript. The key target determines the desired JavaScript version, ES5 (or a newest release).

Depending on the level of "strictness" for tsconfig.json the compiler and the editor will comply if you don't add the appropriate type annotations to your code (more on this in a minute).

With strict set to true TypeScript enforces the maximum level of type checks on your code enabling amongst the other:

  • noImplicitAny true: TypeScript complains when variables do not have a defined type
  • alwaysStrict true: strict mode is a safe mechanism for JavaScript which prevents accidental global variables, default "this" binding, and more. When "alwaysStrict" is set true TypeScript emits "use strict" at the very top of every JavaScript file.

There are a lot more configuration options available. With time you'll learn more, for now the two options above are everything you need to know for getting started. But what is "any" by the way?

A couple of words on "types"

By now you should've got an hint of what TypeScript does. Everything revolves around types. These are not the classic JavaScript "types" like String, Object, Boolean and so on. TypeScript adds more type on its own like any (and more).

"any" in particular is a "loose" TypeScript type. It means: this variable might be of any type: string, boolean, object, really, I don't care. Which in fact is like having no type checking at all. With strict set to true instead you say to TypeScript "don't allow ambiguity in my code".

For this reason I recommend keeping the max level of strictness on TypeScript, even if it can be harder to fix all errors at first. And now we're almost ready to see TypeScript in action!

TypeScript tutorial for beginners: TypeScript in action

Everything begins with a legitimate (apparently) JavaScript function: filterByTerm. Create a new file named filterByTerm.js in your project folder and copy the following code into it:

function filterByTerm(input, searchTerm) {
  if (!searchTerm) throw Error("searchTerm cannot be empty");
  if (!input.length) throw Error("inputArr cannot be empty");
  const regex = new RegExp(searchTerm, "i");
  return input.filter(function(arrayElement) {
    return arrayElement.url.match(regex);
  });
}

filterByTerm("input string", "java");
Enter fullscreen mode Exit fullscreen mode

Don't worry if you don't understand the logic right now. Take a look at the parameters of that function and at how they are used a couple of lines later. Just by looking at the code you should have already spotted the problem (no it's not Java).

I'm wondering if there is a way to check that function in my IDE, without running the code or having to test it with Jest. Is that even possible? TypeScript is great for that, in fact it's one the best tool for static checking in JavaScript, that is, "testing" the correctness of your code before it even runs.

So take the leap into the TypeScript world and change the extension of your file from filterByTerm.js to filterByTerm.ts. With this change you're going to uncover a bunch of errors in your code:

TypeScript catching bugs

Can you see those red marks under function parameters? From now on I'll show you errors in textual form, but keep in mind that IDEs and text editors display these red line whenever you make a mistake in TypeScript.

To confirm we're doing something wrong run:

npm run tsc
Enter fullscreen mode Exit fullscreen mode

and take a look at the errors:

filterByTerm.ts:1:23 - error TS7006: Parameter 'input' implicitly has an 'any' type.

filterByTerm.ts:1:30 - error TS7006: Parameter 'searchTerm' implicitly has an 'any' type.

filterByTerm.ts:5:32 - error TS7006: Parameter 'arrayElement' implicitly has an 'any' type.
Enter fullscreen mode Exit fullscreen mode

Bingo! TypeScript is telling you that function parameters have the "any" type, which if you recall can be any kind of type in TypeScript. We need to add the appropriate type annotations to our TypeScript code.

But wait, what's a type, really?

What are types and what's wrong with JavaScript?

JavaScript has types and if you worked with the language before you know there are strings, booleans, numbers, objects, and so on. As of today there are seven types in JavaScript:

  • String
  • Number
  • Boolean
  • Null
  • Undefined
  • Object
  • Symbol (part of ECMAScript 2015)

Everything in that list is a "primitive" except Object which is a type. Every JavaScript type has a corresponding representation which can be used in our code, like strings and numbers for example:

var name = "Hello John";
var age = 33;
Enter fullscreen mode Exit fullscreen mode

The "problem" with JavaScript is that a variable can change its type whenever it (or we) wants. A boolean for example can later become string (save the following code in a file named types.js):

var aBoolean = false;
console.log(typeof aBoolean); // "boolean"

aBoolean = "Tom";
console.log(typeof aBoolean); // "string"
Enter fullscreen mode Exit fullscreen mode

The transformation can either be intentional, a developer might really want to assign "Tom" to aBoolean, but there are high chances that these kind of errors will happen by accident.

Now, technically speaking there's nothing wrong with JavaScript itself because its "type dynamism" is intentional. JavaScript was born as a simple scripting language for the web, not as a fully fledged enterprise language.

JavaScript relaxed nature however can pose serious problems in your code, undermining its maintainability. TypeScript aims to solve these problems by adding strong types to JavaScript. In fact if you change the extension of types.js to types.ts you'll see TypeScript complaining in the IDE.

The compilation of types.ts will produce:

types.ts:4:1 - error TS2322: Type '"Tom"' is not assignable to type 'boolean'.
Enter fullscreen mode Exit fullscreen mode

Armed with this knowledge let's dig deeper into TypeScript types.


Stay tuned for part 2!

Top comments (0)