How to install Typescript and start a project with its unit test – tutorial 2022

Last update April 18, 2023 at 07:09 AM

In this tutorial we will apprendre how to install typescript in ubuntu then implement a functional project with its unit test.

Typescript is a programming language similar to javascript developed by Microsoft.

This language was also used to develop the famous Angular framework that we saw in How to install angular in ubuntu.

Typescript is widely used in the programming of services that will communicate with angular components.

We are not going to discuss the pros and cons of the Typescript language too much. What must be remembered is that this language makes it easy to do object-oriented programming with javascript.

It improves the developer productivity by displaying very clearly the syntax errors during compilation as if it were a native language.

Before learning how to set up a typescript project, we will start by learning how to install Typescript in your favorite OS.

In this tutorial we use ubuntu. If you have problems starting your linux distribution, consider seeing the article Troubleshooting: Linux Won't Launch After Installation.

World's Greatest Computer Scientists

How to install Typescript?

How to install Typescript

To learn how to install typescript my preferred method is to use the name tool. In the rest of this section I will quickly give you the prerequisites you need to install it on your PC.

Prerequisites to install Typescript

Before going any further, you must install the following tools:

  • Vs code : which is currently theIDE par excellence for language
  • Node-js : It is the javascript server that will allow us to use the npm tool.

Install Typescript

After having installed them by following the instructions of their respective sites, you must follow the following installation steps:

  • Create the folder for your project. Let's name it for example project_quickstart
  • Open your code editor vscode then click on File-> open folder -> select project_quickstart 
  • In your terminal (you can use the one vs code to go faster) type:
npm init

If you're opening another terminal, make sure you're in your new project folder by doing:

cd path_to_the_dossier / project_quickstart

After order npm init , you will be asked to configure your project. Press Enter to keep the default configuration. For details, follow the code below:

package name: (typescript-project quickstart) project_quickstart version: (1.0.0) description: entry point: (index.js) test command: 
git repository: keywords: author: license: (ISC) About to write to PATH/Typescript project quickstart/package.json: { "name": "project_quickstart", "version": "1.0.0", "description": "" , "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC " } Is this OK? (yes) yes

When you're done, we continue with the typescript installation command

sudo npm i -g typescript; sudo npm install --save-dev typescript
    • global (-g) install typescript on the whole pc but not on the project. The advantage is that you can directly call the tsc command in the terminal.
    • save-dev install only in the project. What easy to share. To call the tsc command, you will have to write the path to its executable too. Not practical to go faster.

The command sudo npm i -g typescript; sudo npm install --save-dev typescript  is a combination of two. You can choose between the first (before the semicolon) or the second (after the semicolon). Personally I like to use both.

Installation result

[..................] - rollbackFailedOptional: verb npm-session 7a2db726640a577c / usr / local / bin / tsc -> / usr / local / lib / node_modules / typescript / bin / tsc / usr / local / bin / tsserver -> / usr / local / lib / node_modules / typescript / bin / tsserver + typescript@4.0.3 updated 1 package in 48.437s ╭──────────── ──────────────────────────────────────────────── ───╮ │ │ │ New patch version of npm available! 6.14.6 → 6.14.8 │ │ Changelog: https://github.com/npm/cli/releases/tag/v6.14.8 │ │ Run npm install -g npm to update! │ │ │ ╰──────────────────────────────────────────── ─────────────────╯ npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN project_quickstart@1.0.0 No description npm WARN project_quickstart@1.0.0 No repository field. + typescript@4.0.3 added 1 package from 1 contributor and audited 1 package in 2.481s found 0 vulnerabilities

Everything has gone well so far, except that I am asked to update my node js. I will do it later !!!

npm link typescript

Now that we have finished the installation, it is important to use the following command:

npm link typescript

I put it in the title because this important command allows you to use native typescript commands to compile, build and even verify your code. Without this script, any typescript command is void.

Whenever you come back to your typescript project, remember to “npm link typescript” before proceeding. Otherwise you will have mistakes to eat your fingers !!

Here we are, we are done with the installation. If you have followed the steps you will have an EXPLORER of your vscode similar to the one in the image below:

Installing typescript

How to check typescript version?

To verify that Typescript is indeed installed in our project, nothing better than to test by looking for its version.

The easiest way to do this is to manually go to the json package file of your project. This works better especially if you have typescript installed via NPM as in this tutorial.

There is also the method of verification by order, which I've tried personally but doesn't work with all my Angular projects. The reason I will give it anyway at the end of the section.

If this typescript version checking command doesn't work for you, don't panic. Try the first one that you will see in the next section.

Typescript version with npm in manual

This method works if you have typescript installed via npm. To apply it, all you have to do is:

  • to go to the root of your project in Vscode
  • Click on the package.json file

The version of your typescript file is displayed in the package.json file. In the image below, I took care to select it.

typescript npm version

Typescript version in command

In command, just go to your terminal and type:

tsc -v

If you are asked to install node-typescript , that command just didn't work.

Don't rush to install this module because you won't need it in this tutorial or maybe in your next project.

To solve this problem you must:

npm link typescript

Reminds you of a few things, doesn't it? Hope you learned the lesson!!

Now that everything is in place, it's time to configure typescript for the start of our little project.

How to configure typescript?

Now that we have finished installing Typescript, we will quickly see how to configure it.

The configuration is the crucial part that will help us to develop with more ease in the typescript language. To start we will first generate the configuration file tsconfig.json by typing this:

tsc --init

Once done, we will modify the contents of the tsconfig.json file by replacing all the contents with this line of code:

{
  "compileOptions": {
    / * Specify ECMAScript target version: 'ES3' (default). Here ES5 to be compatible with all web browsers * /
    "target": "ES5",
    / * Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. * /
    "module": "commonjs",
    / * Specify library files to be included in the compilation:  */
    "lib": [
      "esnext",
      "dom"
    ],
    / * We want to generate a sourcemap * /
    "sourceMap": true,
    / * All files will be compiled in build directory * /
    "outDir": "./build"
  },
  "include": [
      "src / ** / *"
  ],
  "exclude": [
    "node_modules"
  ]
}

That's it for this part. We will start with the implementation of a typescript project which can be used later as a template for more complex projects.

How to start a typescript project?

Finally here we are. We find ourselves in the most interesting part of the article. I remind you that our goal at the end of this post is to create a minimal project that will work with a unit test. First of all we will create the tree structure of our project which goes in alignment with the configuration of the file tsconfig.json :

  • Create folders and subfolders src / main / typescript in the project root
  • Create file Person.ts (which will be our class in terms of OOP) and put the code below:
export interface Person {firstName: string; lastName: string; } export class GreaterService {great (person: Person) {return`Hi, $ {person.firstName} $ {person.lastName} `; }}

Now that we are done, we are going to test the compilation of the project.

  • Type the command in the terminal
    tsc

You may have a problem like this Cannot find module typescript . If this is your case, click on the link to find the resolution.

Normally if you have followed the typescript installation correctly, you should not encounter any problems.

If all goes well you should notice the appearance of the folder build as well as javascript files Person.js corresponding to its typescript file. Your vscode Project Explorer should look like this.

Implementation of the project

If you obtained a similar result, it is because the file tsconfig.json is well configured.

Installation of tools for typescript unit testing

To do the unit test we will use the framework Jest created by facebook for React Js. We will install a minimum part of Jest to work with Typescript. Run the following command:

sudo npm install -g jest @ types / jest ts-jest -D; sudo npm install --save-dev jest ts-jest typescript

Once finished we will configure it with this command:

jest --init

We are going to maintain the default configuration by pressing the ENTER key only. The result would be similar to this:

The following questions will help Jest to create a suitable configuration for your project ✔ Would you like to use Jest when running "test" script in "package.json"? … Yes ✔ Choose the test environment that will be used for testing ›node ✔ Do you want Jest to add coverage reports? … No ✔ Which provider should be used to instrument code for coverage? ›V8 ✔ Automatically clear mock calls and instances between every test? … No

We will open the jest configuration file which is jest.config.js. We will add inside the tag module.exports from the script the following code:

"roots": [" / src "]," testMatch ": [" ** / __ tests __ / ** / *. + (ts | tsx | js) "," ** /? (*.) + (spec | test). + (ts | tsx | js) "]," transform ": {" ^. + \\. (ts | tsx) $ ":" ts-jest "},

The end result should look like this:

We will now continue to set up the unit test

At least, the extract.

Creation of test files for the typescript unit test

We're almost there… We're going to get there. In this part of the code we are going to create classes for unit testing.

  • Create the directories src / test / typescript
  • Create the file Person.spec.ts in the previous directory

In the file copy this content:

import {GreaterService, Person} from "../../main/typescript/Person"; describe ('Test Person.ts', () => {let service: GreaterService; beforeEach (() => service = new GreaterService ()); test ('should say', () => {const person: Person = {firstName: 'Tedi', lastName: 'DEV'}; expect (service.great (person)). toBe (`Hi, Tedi DEV`);})});

Now here we are, the real moment has arrived. We're going to test our hard-completed code. For that you have to type the command:

  • jest
  • or : npm run test

In both cases you should get the following result if all goes well:

> jest PASS src / test / typescript / Person.spec.ts Test Person.ts ✓ should say (3 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 0.837 s, estimated 1 s Ran all test suites.

Last update April 18, 2023 at 07:09 AM

Conclusion

We have finally arrived at the end of this tutorial which also served as an introduction to Typescript, I really hope you enjoyed this little project. As a reminder, here is what we saw:

  • How to install Typescript?
  • How to check typescript version?
  • How to configure typescript?
  • How to start a typescript project?

Good luck for your future projects.

How to install Typescript in ubuntu and set up a project with its unit test - tutorial 2022
Image by Free-Photos from Pixabay