Understanding TypeScript & Using it in Your Node Environment.
Tags: typescript, node, javascript, tutorial
Published: 2021-11-15 19:59:29

I struggled with this concept a lot, but let me save you the stress, and explain as simply as I can.


Typescript is just a secure way of writing JavaScript code. Do not get confused by the fancy terminologies people throw around it.

The good news is, if you know JavaScript, you already know ~90% of Typescript. The additional layer only forces you to be a lot more intentional about your variables and data types.

...
### Why Typescript?

Simple answer? To catch errors early in your editor. 
Typescript detects silly bugs at runtime; bugs you probably wouldn’t notice until it’s too late when using pure JavaScript.


...
### Here's sample JavaScript code: 

```Javascript
let id = 1
let company = "GYRO Design Lab"
let isPublished = true
let mandem = ["Dexter", "Mide", "Emmy"]

```

But the unfortunate thing here is that, at some point later in your code, the variable `company` - for instance, could be re-assigned to a value of an entirely different data type, which would be unexpected behavior. 
Sadly, JavaScript will not throw an error, and this poses a compounding threat to your App. 
Thankfully, popular code editors like _**VScode**_ now use Typescript under the hood, to spot errors like these.

...
### Sample Typescript code

```Javascript
let id: number = 10 
let company: string = "GYRO Design Lab"
let isPublished: boolean = true

// Here, the variable "x" can later be re-assigned a value of different datatype
let x: any = "Hello" 

// This is an array of numbers. This - "Number[]", tells the system that the variable "ids" is expected to be an array of numbers. So if you try to push a string in the array, you will get an error.
let ids: number[] = [1,2,3,4,5] 

```

As you can see, with Typescript, you have to explicitly define your Types.

...
When creating an _**object**_, for instance, you get to create an _**interface**_ that defines the shape of your _**object**_;  


```Javascript
// interface declaration
interface User {
	Name: string;
	Id: number
}

// Javascript object which conforms to the shape of the interface. 
const user: User = {
	Name: "Janet",
	Id: 0
}
// Typescript will warn you if it doesn't match.
```

...
### So what exactly happens under the hood?

Typescript code transpiles to JavaScript, which runs anywhere JavaScript runs: In a browser, on NodeJS, and in your apps.


_“Transpiling is a specific term for taking source code written in one language and transforming into another language that has a similar level of abstraction”_ - _**stackoverflow.**_

...
When setting up your Typescript+NodeJS project, your entire project files are usually in a folder, including your Typescript [_**.ts**_] files. 

However, your browser will not run _**.ts**_ files, this is why the Typescript engine automatically generates a new project folder containing the transpiled version of our entire project, which we can now run and test.


...
### Now let's create a simple NodeJS App, and configure Typescript.


* Initialize your project
`npm init -y`


* Install Typescript as dev dependency.
`npm install -D typescript`


* Generate a configuration file - _**tsconfig.json**_
`npx tsc --init`

Now open the _**tsconfig.json**_ file, you will see a bunch of commented-out codes; no worries, look for the properties below, and make these changes to them.
**Note**: Some of the properties below are commented-out by default in the _**tsconfig.json**_ file, you will have to uncomment them.


`”Target": "es6”`
`”rootDir": "./src”` "src" will be the name of your project folder 
`”outDir": "./build”` "build" is the auto-generated folder that will holds your transpiled files.



* In your package.json file, add the following tags into your `"scripts"` key like so;

```Json
"scripts" : {
    "build" : "tsc"
    "dev": "npm run build && node build/index.js"
}
```

`"build" : "tsc"` is responsible for transpiling the Typescript codes to JavaScript, and `"dev": "npm run build && node build/index.js"` runs the program when you type `"npm run dev"` in you console.

...
We have successfully integrated Typescript to our app. Now let's see it in action. 

* At the moment, your root directory should contain _/node_modules_, _package.json.lock_, _package.json_, and a _tsconfig.json_ file. Create a new folder - _src_. Your first Typescript file goes in here.

* create an _index.ts_ file inside the _src_ folder.

* Paste the entire typescript snippet shown at the beginning of this article, into your _index.ts_

* Finally run `npm run dev` in your terminal. You will notice a newly generated folder _/build_, which contains a transpile version of your Typescript code.


Hope you find this helpful.