Introduction to TypeScript

After some time of working with Angular and Typescript, I decided to create a series of articles where I will discuss different features and concepts related to Typescript. 

History

JavaScript is one of the most widespread cross-platform languages, used both in frontend and backend. There is a mismatch between the application’s size, complexity and JavaScript’s ability to manage at a scale. For this reason, Typescript was created by Microsoft to fulfill the needs to develop large, scalable applications. 

Definition

Typescript’s most important concepts are: 

  • Static type system.

Types are checked before run-time, while in JS types are checked during execution. This is an advantage of TS because a lot of errors  can be described as type errors: a value was used where a different type of value was expected. Consider Typescript as a tool which runs before your application to ensure that all the types are correct. 

  • Typescript is a superset of JavaScript.

Consider TS as a layer around JS that offers all JS featured and some extra. We need to point out  that browsers “understand” only JS, so all TS code is transpiled in JS. 

To sum up TS is JS with the benefits of writing better and more readable code due to types. Also another advantage is that types act as a documentation. 

TypeScript  to  JavaScript

Browsers don’t support Typescript, so the source code must be re-written in Javascript. The process of converting TS to JS is known as transpiling and is handled by Typescript Transpiler. tsc options are given in tsconfig.ts that a configuration looks like this: 

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",                 
    "module": "commonjs",                   
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,                        
    "forceConsistentCasingInFileNames": true
  }
}

Typescript config file can contain customizations for these categories:

  1. File Inclusion
  2. Project Options
  3. Strict Checks
  4. Module Resolution
  5. Source Maps
  6. Linter Checkers

All properties are specified in more details here and you can configure it according to your needs.  

Typescript Compiler is using file.ts and options defined in tsConfig.json to generate the javaScript that will be rendered in the browser.  

Create a TypeScript Project

In order to better understand, let’s create a new project following these steps: 

  1. mkdir ts-project
  2. cd ts-project
  3. npm init (Will guide you on creating a new project: npm init -y to use defaults in package.json)
  4. npm i typescript –save-dev (Install TS as a development dependency)
  5.  tsc –init (Will create tsconfig.json file)
  6. Update tsconfig.json by adding the following inside compiler options: 
    1. “rootDir”: “src”
    2. “outDir”: “dist”
    3. “sourceMap”: true

Giving rootDir the value of src means that all TypeScript files will be under source and then after we run tsc -w (-w allows compilation when changes are made), the compilation result will be stored under the dist folder that we configured through outDir property. SourceMap property set to true will create a file that maps the compiled JS Code with TS code. This gives us the possibility to debug the TS file to solve any error that might happen. 

Let’s create a new file enum.ts: 

export enum PRODUCT_CODES {
    PEN ='A1',
    PENCIL = 'A2',
    NOTEBOOK = 'D5'
}
 
console.log('Notebook Code: ', PRODUCT_CODES.NOTEBOOK);

By running tsc enum.ts, TypeScript compiler will generate enums.js inside the dist folder and by running tsc -watch every time we make changes on this file enum.js will get updated automatically. Below you can find the enum.js file.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PRODUCT_CODES;
(function (PRODUCT_CODES) {
    PRODUCT_CODES["PEN"] = "A1";
    PRODUCT_CODES["PENCIL"] = "A2";
    PRODUCT_CODES["NOTEBOOK"] = "D5";
})(PRODUCT_CODES = exports.PRODUCT_CODES || (exports.PRODUCT_CODES = {}));
console.log('Notebook Code: ', PRODUCT_CODES.NOTEBOOK);
//# sourceMappingURL=enum.js.map

If we execute node dist/enum.js, we will see it printed in the terminal “D5”. 

Conclusions

To sum up, in this article we did an introduction to Typescript, how it’s converted to JavaScript and what is tsConfig’s role. Also we went and created a new project in Typescript from scratch. Next article on this series will be about Basic Types. 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s