What does JavaScript do?
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.
What is TypeScript?
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.
Migrating to TypeScript – How it helps
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.
Let’s Get Started!
This Guide will help you migrate Javascript to Typescript which can be a difficult task.
Here are the steps to follow for simple migration:
- Add TypeScript dependencies
- Add TypeScript configuration file
- Updating .js files to .ts/.tsx
- Add type definition for packages
- Add custom type definition for packages with no declaration
- Add interfaces and types where ever required
- Strictly typed
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.
- outDir – Redirect output structure to the directory, change this to ./build
- allowJs – set this to true
- target – this converts newer javascript concepts to older ones set this to ES5
- Include – this should be your source directory where javascript files are present
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 "*.js" -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
let user = {} user.name = “sagar” user.age = 30 user.email = “mymail@gmail.com”
If you get errors such as the ones below:
error TS2339: Property name does not exist on type ‘{}’.
error TS2339: Property age does not exist on type ‘{}’.
You can fix them by updating the code the following way:
const user = { 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 } let user = {} as User; 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:
function add (x,y) { return x + 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.
function add (x: number,y: number ) { return x + 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, implied 'any' type. */ "strictNullChecks": true, /* Enable strict null checks. */ "strictFunctionTypes": true, /* Enable strict checking of function types. */ "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on, functions. */ "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes., */ "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any', type. */ "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source, file.*/
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.