Typescript Cheatsheet Syntax Part 1
Tags: typescript, javascript
Published: 2021-04-15 00:45:31

## What is Typescript?
According to Maximilian Schwarzmüller, "Typescript is a Javascript superset" Typescript is not completely a new language, but Typescript always compiles to Javascript. My analogy maybe is like body(JS) + armor(TS). Typescript makes Javascript is stronger because Javascript is a loosely typed language, and Typescript is a strongly typed language. I will explain what's the difference between loosely typed language and strongly typed language.

Javascript is a loosely typed language because we have the flexibility to assign without declaring a type of variable.

Try to run this snippet below into our browser console.
```js
function sum(a, b){
  return a + b
}

const firstNumber = '2';
const secondNumber = 5;

const total = sum(firstNumber, secondNumber)
console.log(total)
```
![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zo0ub8co78bl1jer460.png) 
 
Yes, of course. The answer is 25. this is one of the problems of javascript is a loosely typed language.

We can check what's the type of parameters, but we must add more chunks of codes there.

```js
function sum(a, b){
  if(typeof a === 'number' && typeof b === 'number'){
    return a + b;
  } else {
    return +a + +b;
  }
}

const firstNumber = '2';
const secondNumber = 5;

const total = sum(firstNumber, secondNumber)
console.log(total)
```

That's why Microsoft develops Typescript. Here is the code of how Typescript solves the problem.

```ts
function sum(a: number, b: number) {
  return a + b;
}

const firstNumber = 2;
const secondNumber = 5;

const total = sum(firstNumber, secondNumber);
console.log(total);
```
We just need to specify the type of the parameter.

## Installation

Install the node.js because we need to install typescript from `npm`

You can download it from [here](https://nodejs.org/en/).

> I would recommend using Node.js Version Manager because it will be great for the future if you want to change the node version easily. I'm using [fnm](https://github.com/Schniz/fnm)

```
npm install -g typescript
```

after you install the typescript globally, you can run this command below to convert `.ts` to `.js`

```
tsc "filename"
```

## Basic Syntax
You can try to clone/fork this [project](https://github.com/raaynaldo/ts-simple-playground), so you can follow along with my tutorial.

Install the packages
```
npm install
```

Compile the Javascript
```
tsc app.ts
```

Start the server
```
npm start
```

Play around in the `app.ts` file

### Primitive Types (string, number, and boolean)
Every type in Javascript exists in TypeScript. `string`, `number`, `boolean` are the primitive types in Javascript. Let's see the chunk of code below.

try to copy to the `app.ts` file in the project.

```ts
function sum(a: number, b: number, message: string, printResult: boolean) {
  const result = a + b;

  if (printResult) {
    console.log(message + result);
  }
}

const num1 = 25;
const num2 = 10;
const message = 'The total is ';
const printResult = true;

sum(num1, num2, message, printResult);
```

Compile to Javascript
```
tsc app.ts
```

Try to change the variable type of `num2` to be a string. It will give you an error message when you compile again.

![alt text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fw7oll38ew5mzzkh5a2n.png)
 
> PS: Typescript will be compiled the code to Javascript even though you have some errors, but there are warning in the console like the screenshot above.

### Object

Declaring the Object type is quite similar with other primitive types.
```ts
const dog: object = {
  name: 'roger',
  age: 3,
};
```
However, we can even specify the attributes of the object.
```ts
const dog: {
  name: string;
  age: number;
} = {
  name: 'roger',
  age: 3,
};
```
So the variable dog can only receive an object with those specific attributes.

### Array

We should declare also what's the variable inside the array, and the array can only receive the variable that has been declared.
```ts
let programmingLanguages: string[];
programmingLanguages = ['Javascript', 'Typescript', 'Ruby', 'Python'];
```

If we want to make the array is flexible with any type, we can use `any` variable. However, it is not good to use it because we remove the idea of strongly typed language.

```ts
let programmingLanguages: any[];
programmingLanguages = ['Javascript', 'Typescript', 1, true];
```

### Tuple

Javascript doesn't have tuple, but programming languages such as C# and Java, have it. So, what is Tuple? A tuple is quite similar to an array, but a tuple is a fixed-length array and the type of each value can be different. 

```ts
let role: [number, string];
role: [1, "Web Developer"]
```

### Enum
When we need to put some contact values, Enum is the answer to our needs.

the value of this enum will start from 0, 1, and 2 because we didn't declare any value.
```ts
enum Role { ADMIN, READ_ONLY, AUTHOR }
console.log(Role.READ_ONLY); // 1
```

If we declare a number in the first enum, the following value of the enum will be increased.
```ts
enum Role { ADMIN = 5, READ_ONLY, AUTHOR }
console.log(Role.READ_ONLY); // 6
```

Enum mustn't declare the number, but we can also declare to string.
```ts
enum Role { ADMIN = 'ADMIN', READ_ONLY = 'READ_ONLY', AUTHOR = 'AUTHOR' }
console.log(Role.READ_ONLY); // READ_ONLY
```

Enum Typescript documentations is [here](https://www.typescriptlang.org/docs/handbook/enums.html)

### Any
Any is the special type in Typescript. Any can receive any type in the variable, so it loses the strict of Typescript. I don't recommend using it all the time.

```ts
let anyType: any;
anyType = 1;
anyType = "hello";
anyType = [1,2,3];
anyType = {};
anyType = false;
```

### Union Types
union type let the variable receive more than one type by using `|`

```ts
let id: string | number;
id = 10; // Ok
id = "ID001"; // OK
id = [1, 2]; // Error
```

### Type Aliases
We can change the type name as we want, but it will be useful for complicated types such as object and union.

```ts
type ID = string | number;
let id: ID
id = 10; // Ok
id = "ID001"; // OK
id = [1, 2]; // Error
```

### Literal Types
This type lets the variable only receive the same value that has been declared.

```ts
let alwaysOne: "One";
alwaysOne = "One"; // OK
alwaysOne = "Two"; // Error
```