DEV Community

Cover image for [ReactJS] From Javascript to Typescript
Atif Aiman
Atif Aiman

Posted on

[ReactJS] From Javascript to Typescript

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!

npm install typescript @types/node @types/react @types/react-dom @types/jest --dev
Enter fullscreen mode Exit fullscreen mode

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.

type YourVariable = string;

// is equivalent to

const yourVariable: string = "Hello DEV.to";
Enter fullscreen mode Exit fullscreen mode

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.

// One type
type VariableOne = string;
// More than one type
type VariableTwo = string | number;
// Object of types
type ObjectOne = {
  paramOne: string;
  paramTwo: number;
};
Enter fullscreen mode Exit fullscreen mode

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.

interface ObjectOne {
  paramOne: string;
  paramTwo: unknown;
}
Enter fullscreen mode Exit fullscreen mode

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

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

// This function will accept `paramOne` as a string and `paramTwo` as a number and will return boolean
Enter fullscreen mode Exit fullscreen mode

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

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

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

// Step 2: Call your type
const varOne: VarOne = "";
Enter fullscreen mode Exit fullscreen mode

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.

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

// Or, the far better way, and more readable!
type VarOne = {
  paramOne?: string;
};
Enter fullscreen mode Exit fullscreen mode

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.

const Home: React.FC = () => {
  return (
    <div></div>
  );
};
Enter fullscreen mode Exit fullscreen mode

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?

const Home: React.FC<{ paramOne: string }> = ({ paramOne }) => {
  return (
    // Your JSX
  );
};
Enter fullscreen mode Exit fullscreen mode

Want to make your code cleaner?

type HomeProps = {
  paramOne: string;
}

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

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 and TS-React Cheatsheet to learn more about them.


Bonus Content

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

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

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

type ObjectOne = any;

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

const {
  paramOne,
  paramFour = "Holla",
}: { paramOne: string, paramFour?: string } = objectOne;
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (7)

Collapse
 
lucastvms profile image
Lucas Vieira

Great tutorial, thanks for the explanation 😃👍

Collapse
 
danielo515 profile image
Daniel Rodríguez Rivero

Verbosity. It means that you can read your code better, since you know what every function requires, along with its type.

Or worse because the function signature takes 3 paragraphs....

Collapse
 
alserembani profile image
Atif Aiman

Well, that hits the spot 😂

Collapse
 
gevik profile image
Gevik Babakhani

Good article. TypeScript has become my first choice when developing for the web. I use it both for the backed and frontend.

Collapse
 
khalidtoor profile image
khalidtoor

Great details 👌

Some comments may only be visible to logged-in visitors. Sign in to view all comments.