As the javascript projects have become more and more complex. More and more developers started using static type checking. They use static type checking to prevent bug and errors in code during code compilation.
This article explains how to adapt static type checking for React. And how to use static type checking in your React project.
JavaScript is described as dynamic, weakly typed, and loosely typed. It means that type checking of values is performed at runtime, rather than compile time. Technically, all the expressions listed below are syntactically valid but will give type errors at runtime.
false + 1
[ ] + 5
“ “ + 9
info
Type errors arise when operations are carried out on values that do not support that operation. To avoid this, there is a method called static type checking. The method is explained further in this article. Before beginning, make sure Node 8+ is installed on the system.
Static Type Checking in React
There are two ways to add static type checking in React:
These tools help by enforcing, ensuring, and verifying the use of a correct type of property. Static type checking helps with identifying type errors before runtime. The developer workflow is also improved with type checking as it adds auto-completion, assists with variable and function annotation, and identifies mistakes early.
Benefits of Type Checking
There are several benefits of static type checking in JavaScript. A few of them are listed below:
- Detection of errors in the early stage
- Optimized and easy to read
- Better IDE support
Detection of Errors in the Early Stage
Type checking can detect errors and bugs at the early stages of production without running the program. For example, static input and output types could be specified for the calculateSum()
function to prevent the user from inputting the string value. Because the error is detected in the early stages, it is less expensive as compared to finding out about the bug once it has been delivered to the client.
Optimized and Easy to Read
Type checking also helps with the optimization of code. It serves as documentation for both the developers and the other team members. Although comments can also be used in the code for better readability, type structures follow a defined syntax and are not out of date.
Better IDE Support
Another benefit of type checking is better Integrated Development Environment (IDE) support. Since type checking follows a defined structure and syntax, IDEs can auto-check the code and make suggestions to improve the overall quality.
How to Use Flow in React Project
Facebook has created this easy-to-use type check for React developers. As compared to TypeScript, Flow is not an actual programming language; instead, it is a linter that checks codes for type errors. Flow can be easily added or removed from the code as it is adaptable. To learn the basics about Flow, visit the documentation here.
To add the Flow to the project, follow the steps listed below:
- Adding Flow as a dependency to the project.
- Separating Flow syntax from the compiled code.
- Including type checking annotations and running Flow.
Adding Flow as a Dependency to the Project
To get started with Flow, bootstrap a create-react-app with the following command:
npx create-react-app flowchecker
# or
yarn create-react-app flowchecker
Next, navigate to the project folder and add Flow to the project with the command with npm or yarn command:
npm install --save-dev flow-bin
# or
yarn add -D flow-bin
It will install the latest version of Flow in the project. After the installation, add Flow in the scripts section of the package.json file.
“scripts”: {
“flow”: “flow”
}
Lastly, run Flow with this npm or yarn command to set it up.
npm run flow init
# or
yarn flow init
Running this command will add a Flow config file. Config file enables Flow to decide which file to work with and which file to ignore. This is suitable for newer projects. Otherwise, it will get too noisy for existing projects. To disable Flow from carrying out static checking on node modules, add it in the ignore section as shown below:
[ignore]
.*/node_modules/.*
.*/src/registerServiceWorker\.js
.*/src/index\.js
.*\.test\.js
[include]
[libs]
[lints]
[options]
all=true
[strict]
note
This configuration will check all files except node modules.
Including Type Checking Annotations and Running Flow
To begin using the Flow, open the App.js file and write:
// @Flow
This step will enable the Flow to type check in that particular file. Make sure to add this line at the beginning of the file.
To run the Flow project and check for errors, run one of the commands below.
npm run flow init
# or
yarn run flow init
A message like this will be displayed if there are no errors.
No errors!
Done in 0.18s.
Flow also provides plugins for most famous code editors such as Atom, VSCode, Sublime Text, and WebStorm. Moreover, Flow infers types automatically. That explains a developer is not required to write type annotation. It is automatically inferred by Flow, as shown in the example below:
// @flow
function calculateSum(a, b) {
return a + b;
}
calculateSum(3, 4); // Works!
// $ExpectError
calculateSum(true, false); // Error!
How to Use TypeScript in React Project
The second way to perform type checking in Javascript is TypeScript. It is a language developed by Microsoft with its compiler. It is like a typed superset of Javascript as stated on its official website, and it is suitable for checking errors before runtime. Here, the word “typed” means that the programmer has to declare the data type of a variable. “Superset” implies that all the features of JavaScript and TypeScript can be used by a programmer.
info
The extension for TypeScript is file .ts which is the default extension. Another special extension is .tsx which is used for files containing JSX. TypeScript is much faster than Flow and it has more features.
To use TypeScript in a React project, the following steps are to be followed.
- Adding TypeScript to the project.
- Configuring the compiler.
- Running TypeScript.
Adding TypeScript to the Project
TypeScript can be added to a React project in multiple ways. The easiest way is to add TypeScript when creating a new project. To achieve this, execute the following command using npm or yarn. This command will create a basic React project with TypeScript settings.
npx create-react-app my-app --template typescript
# or
yarn create-react-app my-app --template typescript
However, TypeScript can also be added to an existing React project. To add TypeScript to an existing project, first, run this command:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
# or
yarn add typescript @types/node @types/react @types/react-dom @types/jest
The above commands will automatically configure TypeScript in the current project. Next, rename any file to the TypeScript extension (for example, from index.js to index.ts) and restart the development server. This will enable the TypeScript compiler.
TypeScript can also be configured manually in a React project. To manually install and set up TypeScript in a project, run this command in the terminal:
npm install --save-dev typescript
#or
yarn add --dev typescript
This will ensure the successful installation of TypeScript.
Configuring the Compiler
Now, to add the tsc
command, navigate to package.json
and add this command in the scripts section.
“scripts”: {
“typecheck”: “tsc”
}
Then, execute the following command using npm or yarn:
npx tsc --init
# or
yarn run tsc --init
Running this command will add a tsconfig.json
file. The TypeScript compiler provides numerous configuration options. For details on the compiler configuration, check this documentation.
caution
The TypeScript compiler takes typescript files and generates javascript files, so make sure that all source codes are in one place. Ideally, all source codes are under the src
folder.
Running TypeScript
To run Typescript, run the following commands:
npm run typecheck
# or
yarn typecheck
This will successfully build the TypeScript in the project.
Concluding Thoughts
Static type checking is used to prevent bugs and errors from appearing at runtime. For static type checking in React, you can use Flow or TypeScript. There is a clear difference between both. TypeScript is robust when it comes to functionality, while Flow is potentially all that is needed for type checking.
TypeScript has a greater community and long-term support, if that is the end goal, then TypeScript seems to be a better choice. However, Flow is worth the shot for programmers who are seeking a lightweight approach. In this article, static type checking, the benefits of type checking, and both types of tools are discussed to type-check a React app to detect errors and bugs before runtime.