Moving From JavaScript to TypeScript: Things Developers Should Know
You must have heard that typescript is the superset of Javascript. It is because, all Javascript code is valid for typescript as well. But, the added benefit of typescript is that it offers easier detection of errors before execution which is absent in Javascript.
Let’s say you have started a project in javascript and it needs to be migrated to typescript. But you have come so far in your project that starting from zero in typescript will be tedious. So, in this article, we will discuss why developers still go with typescript for the completion of their projects. Before diving, let's understand why you should use typescript.
Why Should You Use Typescript?
Some features of typescript like functions with REST parameters and optional parameters, generic and modules support to compel the user to use it. Using typescript will make the JS code more efficient by making its code easier to read and debug, thus finding errors easily. So, developers get ready to save your time. Below, you can find reasons why TypeScript is becoming famous among developers.
- Strong Static Typing: In Javascript, datatype errors are spotted only at runtime but typescript offers strong static typing. Here, once you declare, a variable doesn’t change its type. The compiler gives heads-up about the type-related mistakes. It gives a better performance during execution and reduced error code.
Typescript doesn’t force developers to declare types everywhere and gives them to freedom to change the level of type strictness at different levels of a project.
- Early Detection of Bugs: Typescript finds bugs at the compile stage which saves a lot of time for a developer. It allows them to spend time correcting logic rather than catching common mistakes.
- Fast Refactoring: In typescript, refactoring multiple files at a time is painless. If you want to improve your app, rename the components, or change the object; it will keep your codebase robust. Typescript spots the bugs so it will simplify the refactoring. With IDEs commands, you will be able to use navigation tools like “find all references” or “go to definition.”
- Reduced Boiler Plate Tests: Typescript assures the passing of correct variables into the correct places, so you won’t be distracted to test them all. It gives you more time to focus on app logic than writing integration test cases.
- Supports Rich IDEs: Typescript supports rich Integrated Development Environments(IDE) that ensure a boost in the productivity of a developer. These IDEs provide features such as autocompletion, auto navigation, and suggestions so that developers can write robust and maintainable code.
Now, we know why developers would be interested to move from JavaScript to Typescript, let’s see how does the process look like.
Moving from Javascript to Typescript
The good part is that if you know JavaScript, you already know much about typescript. TypeScript files have .ts or .tsx as extension. Browsers don’t acknowledge typescript, so its code is compiled to plain JavaScript code. Now let’s start the main steps:
- Placing Your Directories
The part of your project that you’ve written in JS must have .js files in the lib, src, or dist directory. These files will be used as inputs in typescript to run the output you desire.
While migrating from JS to typescript, separate input files will be needed to prevent Typescript from overwriting them. There will be an output directory for the output files if they need a specific directory for storage.
If you’re executing some intermediate steps on JS like bundling or working with a transpiler like Babel, then you already have a folder like this setup.
Check if you have a tests folder outside of the src directory. If it is true, then there will be 2 tsconfig.json, one in src and another in tests.
Here are some references for the keywords used:
- With includes: Reading files in the src directory.
- With allowJS: Receive JS files as inputs.
- With outDir: Discharge output files in-built.
- Placing Typescript
Tsc is a compiler that compiles the typescript code for browsers to understand it. There are two ways of doing it:
- Being Part of React Project
You can use CRA(create-react-app) tools to build a new project in React configured with TypeScript.
npx create-react-app my-app --template typescript
(OR)
yarn create react-app my-app --template typescript
There is no special configuration needed like editing a tsconfig.json file as everything is done by CRA tools. Just run the project as we run react project.
- Being Part of the npm Project
Once the last step is executed, the tsconfig.json file is generated which is stored in the root directory of the project. It has options and settings stored for the tsc compiler.
We will make a separate src directory for our typescript files and a dist directory for javascript files.
"
mkdir src dist
"
Open your project in the code editor and write these two lines in the tsconfig.json file:
“outDir”: “./disc”
“rootDir”: “./src”
This will tell tsc where JS files are placed and where to find TS files.
The common property of tsconfig.json is ComplileOptions. It is an object which is used to change the method through which TypeScript transcript files in JS. It can be done by setting its value to TRUE.
For example: in CompileOptions, if noImplicitAny: true and strictNullChecks: true, then it is a sign of confirmation that our .ts files will check for “types”.
- Start Moving to Typescript Files
There is no need to migrate all the JS files. You can keep those you want in JS format. You can start by renaming your JS files or changing the extension from .js to .ts or .tsx(if you are using JSX). When you open a newly built file in a code editor that supports TypeScript, you may come across some errors. Try to resolve those errors keeping in mind the TypeScript features.
A common error: “cannot find a module”
This is a very common error that you may face which points to some modules that might be missing in your import statements.
Simplifying, it refers to modules that are not defined in the declaration file of the project. To resolve them, you’ll have to install those missing modules using the prefix “@types”.
@types is the package name or a customized version of a package for typescript. For instance: If an error pops up “React is missing”, then you can install @types/react by:
npm install --save-dev @types/react
Types
In JS, a variable type is determined dynamically during runtime. One benefit of typescript is assigning types to variables. It enhances the readability of the code and thus reduces the chances of bugs. Remember the given remarks while assigning values to variables:
- “Any” type: it points to dynamic type. It is similar to removing type checking for a variable.
- “Null or undefined:” if any variable in your code is null or undefined, then we can explicitly tell that it isn’t with an exclamation mark.
Some common examples of type include “number”, “string”, and “boolean”.
- Adding Properties To An Object
But using the same code in Typescript will show errors like name and age property don’t exist in parent variable having the type {}.
Or these can be defined in separate interfaces. For eg,
Advantages of Typescript over Javascript
To assure you of the decision of moving from JS to typescript here are some advantages:
- With typescript, you can use highly productive development tools like static checking for JS IDEs and practices.
- To support the latest browser, you can compile the typescript code according to ES5 and ES6 standards.
- Typescript is structural and not nominal, so developers get ready to save time.
- You can enjoy all benefits of ES6(ECMAScript 6), thus more compatibility and productivity.
- By type-checking the code, developers can avoid tedious bugs which otherwise would be difficult in JavaScript.
Final Thoughts
Moving from javascript to typescript is not that tedious if you follow the proper steps since every JS code is a valid typescript code. You can choose to convert the files where you require strict typing and keep the other files without a change.
So, it depends on you whether you wish to migrate all files from the beginning of the shift to typescript only for a project. It is all flexible for you. We hope that it helps your project.