To transition from JavaScript to TypeScript, the following requirements must be met:
- You are familiar with JavaScript.
- You understand the patterns and build tools utilized in the project.
Let us consider a scenario where we need to transform JavaScript files into TypeScript. It is understood that compiling a TypeScript file generates a JavaScript file with an identical name. In this context, it is essential to make sure that the original JavaScript file, which serves as the input, is not located in the same directory to prevent TypeScript from overwriting it.
Based on the previous discussion, we will operate under the assumption that our directory is organized in the following structure. In this case, we have stored all output files within a directory named "built."
We can use the following process to migrate from JavaScript to TypeScript:
- Add a tsconfig.json file to project.
- Integrate with a build tool.
- Moving all .js files to .ts files.
- Check for errors.
- sing third-party JavaScript libraries.
1. Add tsconfig.json file to project
Initially, it is necessary to create a tsconfig.json file within our project. TypeScript utilizes the tsconfig.json file to oversee the compilation settings of our project, including the specification of files to include or exclude.
{
"compilerOptions": {
"outDir": "./built",
"allowJs": true,
"target": "es5"
},
"include": [
"./src/**/*"
]
}
In the above file, we are specifying a few things to TypeScript:
- The include option reads all files in the src directory.
- The allowJs option accept all JavaScript files as inputs.
- The outDir specifies that all of the output files should be redirected in the built folder.
- The target option specifies that all JavaScript constructs should be translated into an older version like ECMAScript 5.
2. Integrate with a build tool
It is widely recognized that numerous JavaScript projects incorporate a build tool such as gulp or webpack.
Note: Each build tool is different.
There are several methods to incorporate projects with webpack:
a) Run the following command on terminal:
$ npm install awesome-typescript-loader source-map-loader
In the context of webpack integration, we employ awesome-typescript-loader (a loader for TypeScript) in conjunction with source-map-loader to facilitate simpler debugging of the source code.
b) Integrate the module configuration settings within our webpack.config.js file to incorporate the subsequent loaders:
module.exports = {
entry: "./src/index.ts",
output: {
filename: "./dist/bundle.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{ test: /\.tsx?$/, loader: "awesome-typescript-loader" }
],
preLoaders: [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ test: /\.js$/, loader: "source-map-loader" }
]
},
// Other options...
};
3. Moving all .js files to .ts files
In this segment, we need to change our .js file extension to .ts. Likewise, if our file incorporates JSX, we should change its extension to .tsx. Upon opening this file in an editor that supports TypeScript, some sections of our code may trigger compilation errors. Therefore, converting files individually facilitates easier management of compilation issues. If TypeScript detects any compilation errors during the conversion process, it can still process the code similarly to how Word prints our documents.
4. Check for errors
Upon transitioning a js file to a ts file, TypeScript will promptly commence Type Checking on our code. Consequently, we receive diagnostic errors pertaining to our JavaScript code. Below are some examples of the errors we might face:
a) We can suppress errors with using any, e.g.:
In the code provided below, the error can be resolved through the use of type assertion.
var foo = 123;
var bar = 'hey';
bar = foo; // ERROR: cannot assign a number to a string
bar = foo as any //Ok
b) Function with less or more arguments:
function display(name, age, height) {
let str1 = "Person named " + name + ", " + age + " years old";
let str2 = (height !== undefined) ? (" and " + height + " feet tall") : '';
console.log(str1 + str2);
}
display( "Rohit", 32);
In the code provided, the function display accepts three parameters: name, age, and height. We can invoke this function using two arguments: "Rohit" and 23. This is entirely acceptable in JavaScript, as JavaScript assigns the value undefined to any argument that is not provided when a function is called.
However, the equivalent code in TypeScript will produce a compilation error: Expected three arguments but received two. To resolve this issue, we can introduce an optional parameter sign for the height argument and annotate our code as follows:
function display(name: string, age: number, height?: number) {
let str1: string = "Person named " + name + ", " + age + " years old";
let str2: string = (height !== undefined) ? (" and " + height + " feet tall") : '';
console.log(str1 + str2);
}
c) Sequentially Added Properties
The following code is very common in JavaScript.
var options = {};
options.color = "red";
options.volume = 11;
In TypeScript, designating the type of options as {} represents an empty object. Consequently, properties such as color and volume are not present and cannot be assigned. However, if we were to place the declarations directly within the object literal, we would avoid any errors:
let options = {
color: "red",
volume: 11
};
Additionally, we can specify the kind of options and implement a type assertion on the object literal.
interface Options { color: string; volume: number }
let options = {} as Options;
options.color = "red";
options.volume = 11;
5. Using third party JavaScript Libraries
JavaScript projects often incorporate third-party libraries such as jQuery or Lodash. To compile files effectively, TypeScript must be aware of the types of all objects within these libraries. Fortunately, TypeScript type definition files for JavaScript libraries can be found at DefinitelyTyped. Therefore, there is no need to install these types externally. We only need to install the types that are relevant to our project.
For example
For jQuery , install the definition:
$ npm install @types/jquery
For Lodash , install the definition:
$ npm install -S @types/lodash
After implementing the modifications to our JavaScript project, we executed the build tool. At this point, we ought to have our TypeScript project transformed into standard JavaScript that is executable in the browser.