Blog hero curve

FELIPE CABRERA | October, 2022

The ABCs of Typescript

In this article we’ll talk about some basic principles of typescript, how to start a new typescript project on node.js and why it should be added to your dev toolkit.

Technology

If you are a JavaScript developer, TypeScript is a really good tool for you as it always points out the compilation errors at the time of development (pre-compilation).


So what is TypeScript? Is a programming language launched in 2012 developed and maintained by Microsoft, it’s a syntactic superset of JavaScript which adds static typing.
Superset means that it adds features on top of what JavaScript already offers. Because of this, existing JavaScript programs are also valid TypeScript programs.

This means that TypeScript adds syntax on top of JavaScript, allowing to declare and use types from the most basic such as primitive types (string, number, boolean, undefined, null, etc) to much more complex ones.

Something important to know is that TypeScript code actually compiles into JavaScript code because browsers can’t read TypeScript as it is, and it’s at this moment that all types are checked during the build/compilation, and only if everything is ok the program will run.


TypeScript allows specifying the types of different data being passed around within the code, and has the ability to report errors when the types don't match, this is one of the main benefits it has over JavaScript which is a weak typed language were it can be difficult to understand what types of data are being passed throughout the code.

TypeScript's syntax basics

Declaring Types:

When we want to declare a type of a simple variable the syntax is pretty simple, you just add a colon and its type to the right of whatever you're declaring. For example:


1let thisIsAString: string = "I’m a string";
2let thisIsANumber: number = 10;
3let thisIsABoolean: boolean = true;

Once we’ve typed the variables Typescript will make sure this types doesn’t change in the future, and it will show an error in case we try to do so, as it’s shown bellow:


1let thisIsAString: string = "I’m a string";
2let thisIsANumber: number = 10;
3let thisIsABoolean: boolean = true;
4
5thisIsAString = 100; // Type 'number' is not assignable to type 'string'.ts(2322)
6
7thisIsANumber = "Now I'm a string instead of a number"; // Type 'string' is not assignable to type 'number'.ts(2322)
8
9thisIsABoolean = "Now I'm a string instead of a boolean"; // Type 'string' is not assignable to type 'boolean'.ts(2322)

We could also add a [ ] at the end of the declared type for typescript to know it’s an array of values of that type, for example:


1let thisIsAnArrayOfStrings: string[] = ['string1', 'string2'];
2
3thisIsAnArrayOfStrings = 'string'; // Type 'string' is not assignable to type 'string[]'.ts(2322)

Typescript also allow us to declare more than one type to a single variable: this is handy in many situations where we may have different value types returning to a variable.

For example, in case we are making a query to an API and the response may be the data we asked for or undefined in case that data is not available. The syntax for declaring this two types would be pretty similar to the one mentioned above but indicating the two types separated with the pipe symbol “|”.

Let’s see how would it be:


1let thisIsAStringOrUndefined: string | undefined = 'I’m a string';
2
3thisIsAStringOrUndefined = undefined;

In this case no error would be shown as we’ve told TypeScript that the variable may be of type string or undefined.

Interfaces

When working with objects Typescript has different syntax to declare its type, one of the most common one is to use the interface.


Interfaces syntax is pretty similar to an object structure, were we use the interface keyword followed by the name and no equal sign or commas.

This is an example:


1interface Person {
2 name: string;
3 age: number;
4 hasDriverLicence: boolean;
5 spokenLanguages: string[];
6}

In this case we’ve declared the Person interface so now if we want to create an object typed with this interface, Typescript will make sure we follow this structure of keys and types.

For example:


1interface Person {
2 name: string;
3 age: number;
4 hasDriverLicence: boolean;
5 spokenLanguages: string[];
6}
7
8const peter: Person = {
9 name: 'Peter',
10 age: 35,
11 hasDriverLicence: true,
12 spokenLanguages: ['English', 'Spanish']
13};

We’ve created the object peter typed with the Person interface, if we try not to follow the interfaces types or structure Typescript will show us an error.

Conditionals

If for example we wanted to make a conditional key, allowing it to be present or not, we just need to add a question mark at the end of the key in the interface, as we can see bellow:

1interface Person {
2 name: string;
3 age?: number;
4 hasDriverLicence?: boolean;
5 spokenLanguages: string[];
6}
7
8const peter: Person = {
9 name: 'Peter',
10 spokenLanguages: ['English', 'Spanish']
11};

In this case typescript won't give as an error because before we've told that those keys are not absolutely necessary.

How to start a very simple TypeScript node.js project

Here we will explain how to start a new Typescript node.js project step by step. It's important to know we must have node.js installed in our computer for this tutorial to work.


First of all we need to start a new node.js project in our computer, for this we need to open the folder we want to save our project in with our code editor, and open a new terminal and run:

  • npm init --y

This will create our package.json file.

Then we’ll need to install the following dependencies:

  • @types/node: This package contains type definitions for Node.js.
  • ts-node: Allows to run typescript files directly, without the need for precompilation using tsc.
  • typescript: TypeScript compiles to readable, standards-based JavaScript.

We’ll install them as dev dependencies, so the command we should run on our terminal would be the following:

  • npm i --save-dev @types/node ts-node typescript

Now we should be able to see in our folder the node_modules folder and the package.json and package-lock.json files.


After finishing the two previous steps we should initialize the typescript compiler, for this we should run on our terminal

  • npx tsc --init

We could also make some configurations as we initialize the compiler, for example we could run the following command:

  • npx tsc --init --rootDir src --outDir build --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowjs --noImplicitAny

--rootDir src: We are telling the compiler that the source components of our project will be on the src folder.

--outDir build: We are telling the compiler to save the build compiled files on a folder named build.

--esModuleInterop: For use importing and exporting modules throughout the project.

--resolveJsonModule: For working with JSON modules and generating a type for the import based on the static JSON shape.

--lib es6: We are telling we will be using ECMAScript 6.

--module commonjs: We are telling to transpile to common JS so that every browser could read it.

--allowjs: We are allowing JS files in the project.

--noImplicitAny: If there’s no declared type we are configuring not to imply it’s an any type.


Once we’ve donde this a tsconfig.json file with our TS compiler configuration will be created.

Now we should create a folder called src on the root of the project and inside it a index.ts file, were we could write a console.log(“Hello world”), so afterwards this will help us know it’s working fine.

Then we just go to the package.json file and add the following script:

  • "tsNode": "cd src && ts-node index.ts"

Now running:

  • npm run tsNode

On our terminal the index.ts file will execute and we should see the “Hello world” printed on our console!!.

If we want to see the transpiled file from TS to JS we could add the following script on the package.json “transpilation”: “tsc”. Now we could run:

  • npm run transpilation

And a “build” folder will be created with an index.js file in it, this should be the transpiled file from our index.ts.

Conclusion

Hope this brief overview of TypeScript has been useful to you. Adopting Typescript gives you more robust software and easily deployable applications than with regular JavaScript.


Plain JavaScript is more suitable for small projects that require dynamic web applications or mobile and desktop applications, on the other hand, TypeScript is a great choice for developers wherein a large and more complex codebase is involved.


If you are working on a JavaScript project and want to learn more about TypeScript, contact us! We will be happy to help you 🚀

Image attribution: ArthurHidden on FreePick

Share:

Felipe Cabrera
✍️Felipe Cabrera

October, 2022

Typescript is a great tool that help us as developers in our day-to-day job and also enhances our projects code! I highly recommend it!