DEV Community

Jack Chen
Jack Chen

Posted on

Migration to Typescript in a React app

Recently, I was working on a project which started in 2018. It was setup with React, Redux, Mui.. There're quite a lot of features and pages.

Problem or why we move to Typescript

I was assigned to a task that seemed really easy, which is to display the correct phone number for user logged in.

BUT when I digged into that, I found that it's really hard to figure out the shape of profile data for user. The origin data is passing around and name got changed accross different adaptors. To make things worse, the comments are out-dated.

I really want something like this, which makes everything clear:

type OriginProfile = {
   primaryPhone: string,
}

type Profile = {
   phoneNumber: string,
}
Enter fullscreen mode Exit fullscreen mode

How we did it

Basically we did it one component after another. Whenever there's a task that requires us to make changes to the code.
We tried to migrate the related files to typescript. Luck that typescript is a superset of javascript.

Rename as we go

Rename .js/jsx to .ts/tsx.

Infer the shape

To define the shape the data, we have to infer that from the logic in code and the response payload. We did our best to infer and it doesn't matter if we miss something, because we can always add more.

To make the code running

To fix the errors, be flexible and nice.. Just make use of any magic, every error will go away :)
At this point, you should realize you wrote code by guessing.. It's really luck that it worked..

linting

By adding eslint-disable is useful to make code work as well.

remove PropTypes

At this point, I really can't see any benefits to have the PropTypes because Typescript is really helpful in defining the shape. So PropTypes is redundant, that's why we remove it.
Instead we have Interface Props {} for every component.

How's the feeling

It's not easy at the beginning, because I have to figure out how to eliminate all the errors and lots of basic entity typings needed in the project.

But it gets better when you know how to use any and once most of the entity types are defined, not much left indeed, or you can say, it's much easier to add new type.

What's important is that you become much more confident in coding. Typescript will scream if something is wrong. You trust the code, and you know exactly what you're dealing with. Is it a number, string, an object, some complex entity, is it possibly null. You know all that without guessing!

Typescript is awesome and I guess I will never go back.

Top comments (1)

Collapse
 
danytulumidis profile image
Dany Tulumidis

I feel you. Typescript is really nice and its kinda "complete" javascript :D