The question of dynamic vs static data type checking in the world of JavaScript (and thus React) has been around for years now. And honestly, I don’t see a way for it to be finally resolved without taking external factors into account.
Mind you, this is not about right vs wrong or having a sure way to always perform type checking correctly. In fact, it’s all about circumstances and personal preferences (i.e external factors).
Let me explain: In the context of React, type checking takes care of making sure your components are receiving the correct data types for their props.
Whatever the case is, in this article I’m going to be covering what both methods of performing type checking are and how you can achieve them in React.
This particular brand of checking is meant to happen during execution time as opposed to beforehand (which is when static checking happens).
Considering the following working code, would you say JavaScript has the concept of data types at all?
let x = "world";
x = ["hello", x, "!"];
x = x.join(" ");
console.log(x) // hello world !
x.js
It might not have been obvious due to the duck-typing nature of the language, which allows for a level of mutability that makes it very easy to assume there are no types.
But there are and most importantly, there is dynamic type checking. You can see that when you try to add two variables (i.e when using the +
operator). The result of that operation will have very different outcomes depending on the type of their values (i.e it’s not the same to add two strings than to try and add two numbers, or, why not, adding a string and a number).
And just to be clear: if you’re still thinking that the above behavior means “no types”, the actual result for a no-types system would be for the language to interpret all values in the same way, taking into account their numeric representation (after all, that’s what they are to the computer). So adding two strings, would result in a numeric value representing the addition of the bytes that comprise those strings. You could potentially later re-create a new string from that number, but of course, it wouldn’t be the concatenation you’d expect.
The upside to this type of checking is that there are no tools required to have it available in your projects. After all, JavaScript was built with it in mind.
Of course, there are other benefits to this behavior, such as:
One could also argue that there is a downside to this approach as well, and just like with everything, it would be true. After all:
To further showcase what I mean by careless developer-induced bugs, here is a very simple example:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
let currYear = (new Date()).getFullYear()
let age = currYear - event.target.value;
this.setState({value: event.target.value, age: age});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Year of birth:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<h2>You're {this.state.age} years old</h2>
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
simple-component.js
The component is very straightforward, and yes, not that accurate, but you get the basic gist of it. With this code, you can see how the browser’s engine is performing dynamic checks whenever you enter anything into the input field.
But what if you (or anyone else using your component) decides to input anything other than a number? If you don’t have control over the input, the user could be entering any type of content in the field, and thus, generating a NaN (whenever the entered value is not a number).
You can see how the rendered result can be affected by the user thanks to the devs relying on dynamic type checking.
So, what do we do if we want to improve on this? Thankfully, if you’re a React user, you’ll have access to PropTypes, a simple-to-use tool that’ll help you perform advanced dynamic type checking.
To get you started, the latest version of React have removed the PropTypes from its core code base and it can now be installed via npm
:
$ npm install prop-types
You can also include it from one of the CDNs where it resides:
<!-- [UNPKG] development version -->
<script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script>
<!-- [UNPKG] production version -->
<script src="https://unpkg.com/prop-types@15.6/prop-types.min.js"></script>
<!-- [CDNJS] development version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>
<!-- [CDNJS] production version -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
If you go this route, the module will be available through window.PropTypes
.
In any case, once installed, you can use it with your components by defining the static property propTypes
, like so:
class CustomComponent extends React.Component {
render (){
return (
<h2>Hello {this.props.name}!!</h2>
)
}
}
CustomComponent.propTypes = {
name: PropTypes.string.isRequired
}
prop.types2.js
In the example, you can see how we’re setting up the name
prop to be a string and it needs to be present. If the validation fails, then an error will appear on the JavaScript console of your browser.
ReactDOM.render(
<CustomComponent name={123} />,
document.getElementById('root')
);
using-component.js
Using the component as shown above, will generate the following error:
You can use propTypes
to define a lot of different validation types. You have your basic data types (i.e array, bool, func, object, number, string, and even symbol) but you also have more complex options such as checking the shape of an object, or if it’s an instance of a particular class. You can see the full list of options over here.
There is even the possibility to provide a custom validation function, as shown in the following example:
import React from "react";
import ReactDOM from "react-dom";
class Banner extends React.Component {
render() {
return (
<h2>
You're {this.props.age} years old
</h2>
)
}
}
Banner.propTypes = {
age: function(props, propName, compName) {
let value = props[propName]
if(isNaN(value)) {
return new Error("Invalid age value")
}
}
}
class YearForm extends React.Component {
constructor(props) {
super(props);
this.state = {age: 0, birthYear: 0}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
let currYear = (new Date()).getFullYear()
let age = currYear - event.target.value;
this.setState({value: event.target.value, age: age});
}
render() {
return (
<form >
<label>
Year of birth:
<input type="text" onChange={this.handleChange} />
</label>
<Banner age={this.state.age} />
</form>
);
}
}
ReactDOM.render(
<YearForm />,
document.getElementById('root')
);
prop-types1.js
The above example shows how to setup a custom validation function which you can use to make sure the data type entered by the user is valid (in this case, it’s checking if it’s something that can be cast into a number).
If it’s not, then you’ll get an error similar to the one shown below:
Essentially, PropTypes lets you add dynamic data type checks which are much more powerful than what JavaScript has by default. Careful though, this is just for checking the data type of the information you pass to your components, nothing else.
That being said, the errors are not visible unless you know where to look for them (as you’ve seen in the screenshots). This means that the validation doesn’t break execution if it fails, it only reports on what’s happening when the types aren’t properly assigned. And as an added bonus, the custom validation functions allow you to enhance JavaScript’s innate ability to perform dynamic data type checks.
What if this is not enough to you? What if you want an extra level of protection over your code to make sure your project is structured correctly, and everyone working on it is using your code the right way? Enter static type checking.
This type of type-checking is performed before execution, usually during the bundling stage, where you pre-process your code, your stylesheets and, considering that this is another form of code-verification, performing it whenever you do your unit tests is a good idea.
That being said, the concept of static type checking for JavaScript (and thus, for React as well) is “unnatural”, since by definition, the language is weakly typed (or dynamically typed, depending on which definition you want to go with). So performing type checking on React means dealing with the following facts:
NaN
, while 2 divided by 2 would yield a number).With this in mind, the following code would be perfectly valid in JavaScript:
function fn(x) {
if(!x) {
return false;
}
x += 1;
return x;
}
js-code.js
Reading the above code, what would you say is the type of x
or the return type of fn
? Really, you can’t tell, and the language will even try its best to accommodate for some strange, unforeseen use cases, such as:
fn("hello") => "hello1"
fn(_ => 3) => "_ => 31"
fn({prop:1}) => "[object Object]1"
With that in mind I think I’ve answered the following question:
Why would you go through the trouble of adding static type checking into a language that was designed to work without it?
Clearly, trying to avoid scenarios like the ones described above is a very common answer.
Others might include:
I’m sure you can also add some more things to that list, and that alone shows how much potential a static type checker for JavaScript has, so what are our options?
Although the idea (and the added benefits) of having a static type checker in your project might sound so compelling, the actual effort required to do so seems to have hindered most efforts.
Therefore, there are two really useful options out there: Flow and TypeScript.
Using Flow
Flow allows you to add type annotations to your Vanilla JavaScript and then process that code to check for problems.
You can install it with npm
writing:
$ npm install --save-dev flow-bin
You’ll also need to add a few script to the package.json
file of your project:
{
"name": "my-flow-project",
"version": "1.0.0",
"devDependencies": {
"flow-bin": "^0.111.3"
},
"scripts": {
"flow": "flow",
"build": "flow-remove-types src/ -d lib/",
"prepublish": "npm run build"
}
}
package.json
The benefit of using Flow with React, is that if you created your project using Create React App you don’t need to worry about removing the type annotations. That will be done for you.
If you didn’t however, you’ll need to to install Flow’s type-remover (since you’ll need to strip away the added annotations for your code to be correctly interpreted):
$ npm install --save-dev flow-remove-types
That is, of course, assuming your code is inside the src
folder and that you want the final version (the “compiled” JS code,if you will) to be stored inside the lib
folder.
You can then start annotating your code like this (notice the first line, without it, Flow will ignore your files, so don’t forget about it!):
//@flow
function concat(a: string, b: string) {
return a + b;
}
let string1: string = "hello"
let string2: number = 42
concat(string1, string2)
concat-flow.js
Later, if you were to test your code with Flow, you’d get something like this:
Of course, given that the +
operator works for both, strings and numbers, without the annotations, your code would work. This merely ensures you get the results you’d expect from an actual concat function.
You can read all about their annotations here, if you want to know more about them.
Another cool and interesting bit about Flow, is that in some cases, it is capable of inferring expected types without you having to specify them. For example:
// @flow
function square(n) {
return n * n;
}
square("hello world!");
flow-example.js
The above code would fail, because it knows you’re not supposed to use the *
operator with strings!
Using TypeScript for your type checking needs
While Flow allows you to add type annotations which you later need to remove, TypeScript is actually a whole different language built on-top of JavaScript. It provides you with the ability to perform static type checking, which is why I’ve added it here, but it also provides a lot more, so you should check it out if you haven’t yet.
Because of the nature of the language, you’ll have to install a transpiler, which will translate your TypeScript code into JavaScript once you’re ready to test it.
You can do that with npm
with the following line:
$ npm install -g typescript
To check your code and transpile it, you’ll use the following line:
tcs your-file.ts
Notice the .ts
extension, that’s how you tell TypeScript which files to analyze. There is no need to add extra comments in your code like with Flow.
Using the same example we used for Flow (minus the first line), you’ll get this output from TypeScript:
Although it’s a bit less verbose, it provides you with the same type of error Flow did.
However, TypeScript will not try to infer types if you don’t specify them, so the second example, with the square
function will not throw an error here. In other words, if you’re choosing TypeScript, you’ll need to be mindful about the type declarations, otherwise you won’t get the best value out of it.
Before we close this article, I think it’s important to acknowledge the extra effort required to add static type checks into a React project (or any JavaScript project to be honest). Because it’s not just about using the right tool, the language itself does not support it, so there is no workaround here, you’ll need to write a different version of JavaScript and then you’ll have to transpile it in order to execute it.
It adds (at least) one step to your build process, it also requires you to write more code, which if you think about it, goes against one of the main benefits of using JavaScript for web development: less code to write means faster time to market.
This is not to say static type checkers aren’t worth your effort, you just need to make sure it’s the right decision for your current circumstances.
React, just like JavaScript itself, lacks the innate ability to perform static data type checks by default. That being said, there are tools that can help you out in that regard: you can either use external tools or rely on dynamic type checking thanks to PropTypes. The rest of the validation logic is done for you, just like that!
So, what about you? Are you a fan of the PropTypes module? Or do you prefer to check for data type validations some other way? Share your thoughts down in the comments below!
#reactjs #javascript #programming