Understanding TypeScript....My Experience
Tags: beginners, typescript, webdev
Published: 2022-05-13 19:33:32

I decided to look into Typescript this week because of Pavlo (a developer friend who I have never met😆)who has been of great help to me these past few months. You see Pavlo is a JavaScript developer who had just dove into Typescript at his new internship and had run into a bug already while building a new feature for the company and I wanted to help but I didn't know much about Typescript except for the YouTube videos from Fireship✨🔥(the best YouTube channel in the world)…This [TypeScript in 100 seconds](https://www.youtube.com/watch?v=zQnBQ4tB3ZA) video is gold...and so I started doing some learning and what I discovered in the process was a better way of writing JavaScript (Oh well, I was always a strawberry man anyway🤷🏾‍♂️ get it??😀😀). So I decided to write this article on the basics of this cool language or at least try.

## WHAT IS TYPESCRIPT???
Well I already said it is a better way of writing JavaScript but according to official [docs](https://www.typescriptlang.org/), "TypeScript is a **strongly typed programming language** that **builds on JavaScript**, giving you better tooling at any scale" What does this mean??? Let's break it down to two parts: **"strongly typed programming language"** and **"builds on JavaScript"**

## STRONGLY TYPED💪🏾??
No No not that type of strong 😂, this just means that Typescript like other strongly typed languages such as Java and Python will not allow any unholy alliances between values of different types like it would in Vanilla JavaScript.

A very simple example:

```
let Age = 95; //TypeScript immediately assigns the number type to the
 Age variable due to type inference and doesn't allow any other type
 to be assigned//
*Type Inference is the ability Typescript has to assign types for you
 according to the type of value you give to a variable.

Age = Age + 'years old';  // This will produce an error on your IDE 
that Type 'string' is not assignable to type 'number'.

OR

let Age = 95;
Age = '95';  //Type 'string' is not assignable to type 'number'.

```

## BUILDS ON JAVASCRIPT
Behind all the coolness of TypeScript is the fact that the language is literally still JavaScript, same syntax and methods. Typescript is not understood by the browser directly so code written in TypeScript is still compiled down to JavaScript using the TypeScript compiler, It literally creates a JavaScript file with your Typescript code converted to vanilla JavaScript for you, this JavaScript file is what the browser understands.


![TypeScript builds on JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s19jbdidw5npbm30j6ak.jpg)

TypeScript does what we call 'type-checking' in development and in compile time(static type checking) instead of in run time(dynamic type checking) like in JavaScript, Type checking means checking that each operation should receive proper number of arguments and each variable is of the proper data type.. This helps reduce/eliminate type errors when working with numerous variables 

![JavaScript developer ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfdig5grxism40didzj4.jpg)

TypeScript also allows us assign types to variables ourselves (it is advisable to assign types everywhere we can) so we can detect errors in time. 

Example:
```
let Age:number = 23;
let Name:string = 'Mike'; 
let Male: boolean = true
// We are assigning the types that these variables can hold...


```
Here the Age variable will only hold numbers going forward and the Name variable will only hold strings etc. Giving these variables any other data type than the one assigned will produce an error when compiled.

## FUNCTIONS IN TYPESCRIPT
Functions in the TypeScript are the same as in JavaScript with the exception of ability to add types expected for the parameters and also the type expected to be returned from the function.

Example:
```
JavaScript function

function addNumbers(num1, num2) {
  return num1 + num2;
 }
const result = addNumbers(5,10)
console.log(result) //result is 15     

TypeScript Function

function addNumbers(num1: number, num2: number): number //<=return type {
  return num1 + num2;
 }
const result = addNumbers(5,10)  
console.log(result) //result is 15
```
The addNumbers TypeScript function expects 2 parameters of the number type and also expects a number type to be returned from the function , any abstraction from these type rules would produce an error.

Of course you could do without assigning types to function parameters and they will automatically  be assigned the 'any' type which allows for any data type to be passed into a variable or a parameter but then it would be counter-productive because why the hell are you using TypeScript then🤷🏾‍♂️.

## ARRAYS IN TYPESCRIPT

In TypeScript Array types can be set , we can choose for an array to contain strings only or numbers only etc.

Example:

```
let favouritePlaces: string[]; //this array is being set to contain 
only strings and nothing else

favouritePlaces = ['New Orleans', 'French Riviera', 'Bali', 'Bora Bora', 'Santorini']

let Ages: number[];

Ages=[23, 45, 32, 26, 30]

Simple as that!

```

## DEFINING OBJECTS TYPES IN TYPESCRIPT

There are two ways of defining object types in TypeScript:

1) Defining with Interfaces
Interfaces are like templates that describe how objects should look like and what types are given to the values of the objects

Example:
```
interface personObject {
name:string;
age:number;
hobbies:string[];
}

const person1:personObject ={
name:'mike',
age:'56',
hobbies:['movies','sports','coding' ]
}
```
Here we use the personObject interface as a type for the person1 object following the types set for each key-value pair

2) Defining Directly

Example:
```
const person: {
  name: string;
  age: number;
  hobbies: string[];
} = {
  name: "mike",
  age: 22,
  hobbies: ["sports", "cooking", "movies"],
};
```
##TUPLES IN TYPESCRIPT
Tuples in TypeScript are basically arrays but they give us a way of stipulating the types and length of the array before hand.

Example:

```
let myTuple :[string, number, boolean] 
myTuple = ['string', 23, true]
console.log(myTuple)
//Here we fix the length of the array to (3) three values 
of types string , number and boolean
```
## UNION TYPES ( | )
Union types are a special feature in typescript that allow you set multiple types when declaring a variable or setting a parameter, they are represented by the vertical bar ( | ).

Example:

```
let age:(string | number) ;
age = 29; //ok
age = '29'; // still ok

// We can also use this when declaring arrays
`const arr:(string|number)[] = ['Mike', 'Dan', 'Sam', 12, 34, 29]`

```

I have loved getting to learn this lovely ✨ language and will be using it in my future React and Nodejs projects and advice everyone to try it out. I recommend this [video](https://www.youtube.com/watch?v=BwuLxPH8IDs) on Typescript by my goto guy Maximillian Schwarzmuller on his YouTube channel Academind where he goes through the setting up your environment for Typescript.

Thanks for reading👋🏾🙏🏾.