[ReactJS] From Javascript to Typescript
Tags: webdev, typescript, javascript
Published: 2021-11-22 06:56:07

Salam and holla, amigos!

This article can be used other than React as well, but I will focused on React ecosystem, so just skip the React part if you do other than React. 😉

So, today I am discussing how you can move from the Javascript world to the Typescript wonderland. But before that, there is one question you need to ask yourself first, "Why do I need to use Typescript in the first place 🤔?"

Honestly, Typescript might introduce a little bit more learning curve, and maybe a little bit more on syntax, with a trade of shorter and verbose syntax. Of course, there are more to just shorter and verbose.

So, the good of Typescript:
- Moving from type loosed to typed variables and functions. Imagine the reason you didn't get your desired output, just because of "1+1=11". Ridiculous, right?
- Verbosity. It means that you can read your code better, since you know what every function requires, along with its type.
- Developer experience. If you are a lover of IDE such as VS Code, JetBrains or any that supports Typescript support, it helps a lot, and I mean A LOT, so you won't have to play guessing games, plus assisting you when involving team effort. 🤯
- Might introduce a bit of time during setup, but a whole lot easier as you go along, even during you scale up!
- And of course, Typescript also supports ES6 and beyond!

To be fair, I also need to tell you what is the drawback:
- As I said earlier, it introduces a bit of time during setup, and also complexity.
- Might feel irritated at first, because Typescript really hate `any` type 😣, but you will get pass that one day.
- Typescript didn't promise you security, but it promises you lesser bugs to squeeze.
- Since we need to install Typescript on top of Javascript, Typescript needs compiler, thus where Typescript Compiler (TSC) comes in to handle it for you.

Okay, let's dive into the motion!

---

## Installing Typescript

So, do I have to install Typescript? The answer is yes because Typescript is built on top of Javascript, except it later needs to transpile to Javascript. But no fret, Typescript Compiler (TSC) will help you with that, so you just need to create a `.tsx` file instead of `.jsx`.

Don't worry, the installation is relatively easy. Just run this!

```bash
npm install typescript @types/node @types/react @types/react-dom @types/jest --dev
```

If you use any frameworks such as create-react-app (CRA) or Gatsby or NextJS or Remix, I believe there is a better way if you want to initialize the project.

And don't forget, if you want to use Typescript in any of your projects, just change the file extension from `.jsx` to `.tsx`!

---

## Starts with the variable

It all begins with `type`.

```typescript
type YourVariable = string;

// is equivalent to

const yourVariable: string = "Hello DEV.to";
```

There are some basic types available for you. `string`, `number`, `boolean`, `bigint`, and a bit advanced such as `Array`, `Function`. But there is some time, you might get confused or unsure what type you should implement, thus the existence of types such as `unknown`, `never` and `any`. In any event, you have to try to avoid `any` at any cost, but it is not a big problem when you are just learning Typescript.

```typescript
// One type
type VariableOne = string;
// More than one type
type VariableTwo = string | number;
// Object of types
type ObjectOne = {
  paramOne: string;
  paramTwo: number;
};
```

One bit of advice. Don't get too overwhelmed when seeing a really complex typing when reviewing other codes, because the implementation is up to you. As you get better, you will reach there.

Later, involving with class construction (OOP), you will be introduced to `interface`, which behave quite similar to `type` with some differences, but generally, either way is fine.

```typescript
interface ObjectOne {
  paramOne: string;
  paramTwo: unknown;
}
```

My other highlight is the function. You can tell IDE which one is required when passing the parameters as below.

```typescript
type FunctionOne = (paramOne: string, paramTwo: number) => boolean;

// This function will accept `paramOne` as a string and `paramTwo` as a number and will return boolean
```

Later, when you call your function somewhere in your code, the IDE's Intellisense will tell exactly what is needed just as you described in your type. Cool, right?

![VSCode Intellisense and Typescript in action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llg8x20uaihugi78gmrr.jpg)

So, you have created your type, so how to put it in your variables?

```typescript
// Step 1: Create your type
type VarOne = string;

// Step 2: Call your type
const varOne: VarOne = "";
```

Easy right? Told you, it is not hard. You might see this example as simple, wait for a more complex function that requires multiple parameters.

 Want to make your type optional? Here is the way to do it.

```typescript
// Two way of writing it
type VarOne = {
  paramOne: string | undefined;
}

// Or, the far better way, and more readable!
type VarOne = {
  paramOne?: string;
};
```
---

## Typescript and React

So, you have learned about building your types. So is the React! React has several types that can be used when developing your components. For example, `React.FC`, which is for functional components.

```typescript
const Home: React.FC = () => {
  return (
    <div></div>
  );
};
```

`React.FC` is one of the types provided by React that helps you identify what is needed for functional components. So what if you need to pass props?

```typescript
const Home: React.FC<{ paramOne: string }> = ({ paramOne }) => {
  return (
    // Your JSX
  );
};
```

Want to make your code cleaner?

```typescript
type HomeProps = {
  paramOne: string;
}

const Home: React.FC<HomeProps> = ({ paramOne }) => {
  return (
    // Your JSX
  );
};
```

So, that's it about React from Javascript to Typescript. Honestly, the first time I discover TS, I got overwhelmed as well, afraid that the difference is huge. As I have to go through, I fell in love with Typescript and never go back since.

If you manage to reach this far, that means you are just get comfortable with Typescript, but a really lot things you can learn with Typescript such as generic types, etc. But to enter Typescript is not as hard as it seems.

You can explore the [TS Documentation](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html) and [TS-React Cheatsheet](https://react-typescript-cheatsheet.netlify.app/) to learn more about them.

---

## Bonus Content

Before, I wrote an article about destructuring. You can read the article below 👇

{% link https://dev.to/alserembani/javascript-destructuring-the-thing-8ap %}

In the comment section, some ask about how to type destructured variable.

First, if you destructure an already typed object, you don't need to type destructured variable anymore, since the typed parameter will be inherited to the next variable.

![Destructuring typed variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d82xdwp72e10q2xkwcsa.jpg)

Then, if you want to destructure an object that is not typed, there is a way too!

```typescript
type ObjectOne = any;

const objectOne: ObjectOne = {
  paramOne: "",
  paramTwo: 123,
  paramThree: true,
};

const {
  paramOne,
  paramFour = "Holla",
}: { paramOne: string, paramFour?: string } = objectOne;
```

Okay, I will go a bit slow here.

In the first section, I declare an object, in which I didn't know what is in the object, thus I typed it as `any`. This also applies to external JSON data as well.

Then, assume `objectOne` is the data I get from the API somewhere. Casting the `ObjectOne` to `objectOne` is just me simulating the API type.

Below that, I destructure the data, and I put the destructured data type (notice that paramFour isn't inside `objectOne`, but optional in the destructured type). So, that is how you type untyped destructured data.

---

So, that's it! If there is any error or any suggestion, please and please comment down below 👇. I suggest strongly for you to move from Javascript to Typescript, but of course, it depends on your use case.

Until then, amigos. Goodbye, and may be peace upon ya!