Published April 03, 2020. 4 min read
A staple in web development, is versatile but prone to bugs due to its dynamic nature. TypeScript, a robust, compiled language, provides a solution with its strong typing and enhanced development tools. Migrating from JavaScript to TypeScript can enhance code quality and reduce common errors. This guide simplifies the migration process, outlining steps and configurations for a seamless transition.
JavaScript is a programming language commonly used in web development. It is most commonly used as a client-side scripting language and is specifically developed to be a language embedded into a web browser and automate things on the client-side.
TypeScript is a strongly typed, object-oriented, compiled language, Typescript comes with some additional features such as strong-typed variables and object-oriented programming over JavaScript.
TypeScript is open-source. It modifies JavaScript code, making it simple to read and debug. It also provides highly productive development tools for JavaScript IDEs and practices such as static checking.
It helps us avoid critical/functional bugs that developers commonly run into when writing JavaScript by type-checking the code and has many advanced features that help in improving code quality and gets rid of some of the common mistakes easily made in JavaScript.
This guide will help you migrate Javascript to Typescript which can be a difficult task.
Here are the steps to follow for simple migration:
Step 1: Integrating TypeScript dependency Tool
Install typescript globally
npm install-g typescript
This command will install typescript in your project. Make sure you run it inside your project.
npm install typescript
Step 2: Writing a TypeScript configuration file
In your project root directory, type the following command to generate tsconfig.json file.
tsc--init
The file contains most of the configuration features which are commented out by default. We are going to edit this file as per our requirement.
The output will look something like the code below
{
"compilerOptions":{
"module":'commonjs",
"target":"es5",
"outDir":"dist",
},
"include":[
"src/**/*"
]
}
Step 3: Updating from .js to .ts
Rename each file's extension from from .js to .ts (.tsx).
find<package>/src-name-exec sh-c'mv "$0" "${0%.js}.tsx"'{}\;
Only files with .jsx need to be named as '.tsx' or else use '.ts'.
Step 4: Add type definition for packages
If you get errors like “Could not find a declaration file for module xxx.”, they can usually be resolved by running the following command.
npm install @types/xxx
If the error still persists you need to add custom module definition for packages.
Step 5: Add custom Type definition for packages with no declaration
In your src folder create a file with extension .d.ts. Declare the missing module to the file as follows.
declare module"xxx";
Make the following changes to tsconfig.json file to point to your declaration file/folder.
"paths":{
"*":[
"node_modules/*",
"src/types/*"
]
}
Step 6: Add Interfaces and types (wherever required)
The following object will give error in typescript.
letuser={}
user.name="sagar"
user.age=30
user.email="mymail@gmail.com"
If you get errors like “Could not find a declaration file for module xxx.”, they can usually be resolved by running the following command.
error TS2339: Property name does not exist on type '{}'.
error TS2339: Property name does not exist on type '{}'.
You can fix them by updating the code the following way:
constuser={
name="sagar",
age=30,
email="mymail@gmail.com"
}
Or create an interface and use it as below
Interface User{
name:string,
age:number,
email:string
}
letuser={}asUser
user.name="sagar"
user.age=30
user.email="mymail@gmail.com"
“Any” type can also be used for solving the above problem but it is not considered best practice and should be avoided.
Add types to functions:
functionadd(x,y){
returnx+y
}
The above function takes two parameters which can be either string or number, but we want these to be number so we rewrite the functions with types.
functionadd(x:number,y:number){
returnx+y
}
The code should be updated wherever necessary.
Step 7: Strictly Typed
To enable strict type you need to update the configuration file with the following settings.
"strict":true,/* Enable all strict type-checking options. */
"noImplicitAny":true,/* Raise error on expressions and declarations with an, implie */
"strictNullChecks":true,/* Enable strict null checks. */
"strictFunctionTypes":true,/* Enable strict checking of function types. */
"strictBindCallApply":true,/* Enable strict 'bind', 'call', and 'apply' methods on, function */
"strictPropertyInitialization":true,/* Enable strict checking of property initialization in classes */
"noImplicitThis":true,/* Raise error on 'this' expressions with an implied 'any', types */
"alwaysStrict":true,/* Parse in strict mode and emit "use strict" for each source */
Additional setting
"noUnusedLocals":true,/* Report errors on unused locals. */
"noUnusedParameters":true,/* Report errors on unused parameters. */
"noImplicitReturns":true,/* Report error when not all code paths in function return a, value */
"noFallthroughCasesInSwitch":true,/* Report errors for fallthrough cases in switch, statement. */
Enabling the above settings are optional.
Transitioning from JavaScript to TypeScript offers significant advantages in code quality and bug prevention. Through this guide, we've outlined a straightforward process to facilitate the migration, from integrating TypeScript dependencies to enforcing strict typing. Embracing TypeScript empowers developers to enhance readability, minimize errors, and optimize the development process, ultimately contributing to more robust and maintainable code bases.