CodeNewbie Community

Piotr Grzybowski
Piotr Grzybowski

Posted on

My Beginning with TypeScript (TS season one episode one)

That's my first post on code newbies and the first publication of the series of articles I'm going to write about TypeScript. I would like to invite you, my dear reader, to accompany me on this journey so we could learn that skill together.

The sign with 'The journey is on' text on it

Photo by Clemens van Lay on Unsplash

Long story short. After getting some experience of JavaScript I decided to start learning TypeScript. What convinced me is the fact that thanks to TS we can write cleaner and more error-proof code. The other advantage of using a type system is fewer tests that we have to write to make sure our work is done as well as possible.


What is TypeScript?

TypeScript is an open-source programming language developed by Microsoft that compiles to JavaScript. It's been released in 2012 and continues to gain followers every year. By many developers, it's associated with Angular because Angular forces you to use TS.

TS is a superset of JS and valid JS code is also valid for TS. It's like an extension of JavaScript.

The key augmentation that Ts applies to JS is the type system. In case you are unfamiliar with "type", it is a definition that tells you what is intended use of given data. For example, we can have numeric, string, or Boolean types. JS is dynamically typed which means that a variable can contain either text, number, or even a whole object with many sub-objects. TypeScript strictly defines what a given variable can contain. It will return an error if, for example, we try to provide text to a function that requires numeric values.


How to create and setup project with TypeScript

We can easily create projects the same way we create JS projects. Let's start by creating a directory for our new project. I will call my project overlord. Let's create a directory and get access to it.

mkdir overlord
cd overlord
Enter fullscreen mode Exit fullscreen mode

Next, we should create a project with npm. If we use npm init with the -y flag then we don't have to answer all the default questions. After that step, we will have a package.json file with the configuration of our project.

npm init -y
Enter fullscreen mode Exit fullscreen mode

Now, we should install TypeScript and also types definitions for node.js environment. We can do that like shown below.

npm install --save-dev typescript
npm install --save-dev @types/node
Enter fullscreen mode Exit fullscreen mode

In the end, we have to initialize TS in our project. The instruction given below will do that and also it will create a compilation context and tsconfig.json file.

tsc --init
Enter fullscreen mode Exit fullscreen mode

What is the compilation context of TS?

The compilation context is a name for the grouping of TS files that will be parsed and analyzed by a compiler to determine what is valid and what's not. It also contains information about options of the compiler that are in use. We can define mentioned grouping or options of the compiler by using tsconfig.json file.


Compiler options, how to read them?

At the moment your tsconfig.json looks like a mess and contains many commented-out options. Don't worry about it. We will change it to look more legibly. That's how it looks like after changes.

inside of tsconfig.json file

Those are only basic configuration options. There are many more. I recommend checking documentation to get more information. You can find it here.
Now we will go through those options and explain what are they for.

"include": [
  "src/**/*"
],
"exclude": [
  "node_modules",
  "**/*.spec.ts",
  "**/*.test.ts"
]
Enter fullscreen mode Exit fullscreen mode
  • include — specifies an array of filenames or patterns to be included in the program (which files should be included in process of compilation)
  • exclude — specifies an array of filenames or patterns that should be skipped when resolving include (which files should be skipped in compilation)

So it means that our compiler will look for ts files in src directory and all sub directories but it will skip all files with spec.ts or test.ts extension. Mentioned extensions are extensions of tests.

Let’s go now to the compilerOptions section. I remove comments so it will be easier to read.

"compilerOptions": {

    "target": "es5",

    "module": "commonjs",                     

    "lib": ["ESNext"],                        

    "allowJs": true,                         

    "strict": true,                           

    "esModuleInterop": true,                  

    "outDir": "lib",
  }
Enter fullscreen mode Exit fullscreen mode
  • Target sets the JavaScript language version for emitted JavaScript. Default it is ES3. In our case we set ES5.
  • Module specifies what module code is generated (usually CommonJS if target is ES3 or ES5. Otherwise ES6/ES2015)
  • Lib specifies a set of bundled library declaration files that describe the target runtime environment. We used ESNext so it will give us access to the newest features of JS.
  • AllowJs allows JavaScript files to be a part of your program. It’s boolean so we set it on ‘yes’ if we want to include JS files and on ‘false’ otherwise.
  • Strict enables all strict type-checking options. Strict mode guarantees the stronger correctness of our program.
  • EsModuleInterop emits additional JavaScript to ease support for importing CommonJS modules. It provides cooperation between CommonJS format and ES modules.
  • OutDir specifies an output folder for all emitted files. In our case output files will come to the lib directory.

Let’s try to run it

First, we will make a folder for our ts files. It has to be named src just like we set it in our config file tsconfig.json.

mkdir src
Enter fullscreen mode Exit fullscreen mode

Let’s create a file in this folder. I will name my file hello.ts. Next, I will add some simple code in TypeScript to it as shown below.

const sayHello = (name:string) => {
  console.log(`Hello ${name}!`)
}
sayHello('Johnny');
Enter fullscreen mode Exit fullscreen mode

As you can see we set the type of argument name to string. That means if we pass a value of any other type TS will return an error.
Now to compile it just run it by typing tsc in the terminal.

tsc
Enter fullscreen mode Exit fullscreen mode

After compilation ends we can see that we have a lib folder with an output file in JS. Check on that file. In my case it looks like that:

Code in hello.ts

You won’t find any type checking in that code. That’s because the compiler is checking all declarations and returns errors if something is wrong. You can try to pass a value with a different type and see what’s going to happen.

In the end, I would like to also mention that you can use tsc with the -w flag. It turns on watch mode of the compiler so changes are applied live without reloading.

tsc -w
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this article. I hope you stay with me on that TS road and we can together find out how it works and start to use it on an everyday basis. I wish everyone a good day and good luck with all challenges you face.

Discussion (2)

Collapse
andrewbaisden profile image
Andrew Baisden

I'm addicted to TypeScript now, cant get enough of it. Good read BTW.

Collapse
johngidoe profile image
Piotr Grzybowski Author

Hi Andrew,
I am so glad that you like it. I also think TypeScript is a nice tool and future of JavaScript.