How to Migrate a React Component from JavaScript to TypeScript

How to Migrate a React Component from JavaScript to TypeScript

Learn how to easily migrate a React component from JavaScript to TypeScript to improve your project. When migrating over to TypeScript, one basic thing to keep in mind is TypeScript files have a .ts extension instead of .js. Another thing to keep in mind that makes migrating over a breeze is that you can configure your TypeScript compiler to allow JavaScript files.

Learn how to quickly and easily migrate a React component from JavaScript to TypeScript with this simple guide.

As you probably already know, TypeScript is a popular Static Type Checker, built as a superset of JavaScript. TypeScript is really handy for finding type errors before executing them — a rule that is missing from plain Javascript. However, Typescript runs just as smooth as Javascript.

We will assume you started a project in JavaScript and it is too late to start over. So, you have a problem: you want to work in TypeScript, but you are too far along to restart.

What do you do?

In this article, we will cover a way to smoothly and efficiently migrate over to Typescript.

When migrating over to TypeScript, one basic thing to keep in mind is TypeScript files have a .ts extension instead of .js. That’s simple enough. Another thing to keep in mind that makes migrating over a breeze is that you can configure your TypeScript compiler to allow JavaScript files.

As we said earlier, TypeScript is just a superset on top of Javascript — therefore, you can migrate one file at a time and not worry about creating an entirely separate branch for the migration.

Speaking of compilers, it would be nice to leave alone whatever currently bundles or compiles your JavaScript. TypeScript has an easy way to simply add itself on top of your compiler without messing things up. If you’re using npm, you can simply run npm i -g typescript.

Before getting further into the TypeScript set up, one thing to consider is whether your IDE is configured to work with TypeScript. The pre-compile auto-correct TypeScript offers, as well as the ability to detect errors at this stage, are features you do not want to miss out on. If you are using VS Code, support for TypeScript is built in. Otherwise, you will likely need to find a package to get your IDE support for TypeScript.

Typescript compiler

Now you’ll want to add the TypeScript compiler.

Create a file in the root directory of your project named tsconfig.json. There are hundreds of ways to configure this file, but let’s just look at some of the basics.

Before we go into it a bit, instead of creating the file yourself, you can run this command in the root directory of you project:

npx tsc --init

This will create the tsconfig.json file for you, with a few default options turned on, along with a bunch of possible options commented out for you to see.

As you can see, this will be a JSON file. As such, the two common properties to configure here are compileOptions and include.

CompileOptions is an object where options can be set to true to change the manner in which TypeScript transpiles files into JavaScript.

For instance, in compileOptions, we can turn on noImplicitAny: true (if false, TypeScript will infer the type of “any” where no types are defined) and strictNullChecks: true (if false, Typescript will ignore “null” and “undefined”).

With these two options turned on, we can be sure our .ts files will actually check for types. If not, you could run plain JavaScript in .ts files.

The include option is a way to specify the filenames or the glob patterns to match TypeScript files. It is an array which can include specific file names or a pattern all your TypeScript files follow. A simple set up is to simply define this option as include: ["src/**/*"] (*_ matches any directory, while _ matches any file).

This would default to pick any file under the src directory with a .ts, .tsx, or .d.ts extension.

If you add allowJs: true to the compileOptions, the include defined above would also include .js and .jsx files from our src directory.

Short side note: the difference between .d.ts extension and plain .ts is that .d.ts is for declaring things to TypeScript, whereas the .ts is for TypeScript compiling down to JavaScript. The .d.ts is most commonly for declaring types in an npm module for TypeScript to know, while .ts is used for all your JavaScript files. The difference between .ts and .tsx is .tsx is used for JSX files, like React components.

Another basic option to understand is exclude. If you have a wide range in your exclude, there might be certain files you don’t want the compiler to match. For instance, including everything is one option, but then you would probably want to put node_modules under the exclude array.

See the official documentation for more about configuring your TypeScript compiler.

Once you have finished configuring your tsconfig.json file, you can add a script in your package.json to run the compiler. Under scripts, add something like, "tsc:w": "tsc -w". You can then run the script and it will point to your tsconfig.json file and compile away!

@types

If you are using a frontend framework like React, you will need to also install @types packages. Since everything in TypeScript requires type definitions, these packages like @types/react will let TypeScript know the types for all the basic React classes, functions, components, etc.

This is needed to satisfy TypeScript, and rightly so. You will also need to remember to add types to any other library added to your project (e.g. @types/react-router-dom, @types/react-bootstrap, or @types/react-redux).

Another example of the @types packages is @types/node. Without this package, keywords that we are used to, won’t be recognized in Typescript file (.ts file).

For instance, using require to import a package, would return an error like this: Error:(3, 12) TS2304:Cannot find name 'require'. The package @types/node defines this for TypeScript, so we are now allowed to use require without errors.

Some JavaScript packages already have types written in them. These won’t require installing a types packages. However, what if there aren’t types written in the packages and there isn’t a types package to install?

First of all, this is hard to find, as TypeScript has a ton of support. However, if you use TypeScript widely, you will inevitably find a JavaScript package without TypeScript support.

The easy solution here is to simply let the TypeScript complier know your module exists. This won’t add TypeScript to the package, but it will bypass the TypeScript checker and allow you to use it. There are many ways to solve this, like fully adding TypeScript to the package yourself (lots of work in most cases), but this is just a simple solve.

Create a file and name it something like this: MyModuleDesc.d.ts (the .d'ts is the important part).

In that file, simply write declare module "my-module" (with the “my-module” being the package that doesn’t have Typescript). Then, in your tsconfig.json file, under the include array, add the MyModuleDesc.d.ts file (assuming this file is in the root of your project).

typescript javascript react web-development developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

Hire dedicated JavaScript Developers who are proficient in AngularJS, ReactJS, NodeJS, & VueJS frameworks. Get flexible hiring models as per your business requirements.

Make an App with React JS / JavaScript: React and TypeScript

Building a Web Application as a Front-End Developer using React JS and TypeScript! Learn how to use the “Thinking in React” method and apply it to your real web application. We will be using real live weather data to display in our application and make our components reusable and maintainable.

Hire Dedicated React Native Developers - WebClues Infotech

WebClues Infotech is a expert in building iOS, Android Apps, Web apps , Websites, Enterprise solutions. We have crafted many complex and innovative projects that meets our customer expectations.

Hire Dedicated React Native Developer

Have you ever thought of having your own app that runs smoothly over multiple platforms? React Native is an open-source cross-platform mobile application framework which is a great option to create mobile apps for both Android and iOS. **[Hire...