Static vs Dynamic Type Checking in React

Learn what is type-checking and when it’s best to use each of its two forms.

Fernando Doglio
Bits and Pieces
Published in
12 min readNov 26, 2019

--

Image by PublicDomainPictures from Pixabay

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.

Tip: When sharing reusable React components with tools like Bit (Github), use type-checking. It will make your shared components more developer-friendly and less prone to errors.

Example: React components shared on bit.dev

Dynamic Type Checking with JavaScript

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?

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.

How useful is to depend on dynamic type checking then?

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:

  • Faster development type. Since devs don’t have to worry about carefully planning their types and the code to handle them, writing logic becomes a much natural task.
  • Easier-to-read code, as long as the developer builds it with readability in mind. Using the proper techniques you can write code that reads very naturally without having to go through 10 lines of types definition.

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:

  • Careless or inexperienced developers are more prone to adding errors to their logic. These errors should be found during the testing stage, but alas, we’re not covering tests in this article.
  • Having the browser perform these types of checks during execution can take a toll on performance, after all, optimizing code that you can’t trust is not an easy thing to do (not to say there aren’t ways, they’re just harder to implement!).
  • Finally, a common problem you see with tooling surrounding dynamically typed languages, such as JavaScript, is their lack of proper help. It’s very hard to create an IDE that provides the level of intellisense (just to name a single feature here) for JavaScript that Eclipse provides for JAVA for example. It would be amazing if Sublime or even VS Code would do that, but unless you force that extra level of definition into your code (by specially formatted comments, for example), there is nothing they can do about it other than provide basic auto-complete.

To further showcase what I mean by careless developer-induced bugs, here is a very simple example:

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.

Using PropTypes in React

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:

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.

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:

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.

Adding Static Type Checking to your React projects

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:

  • JavaScript has types attached to values
  • Operations with those values react in different ways depending on their types (i.e you can divide 2 by “hello”, and you’ll get NaN, while 2 divided by 2 would yield a number).
  • Variables don’t have a type, so you can use the same variable to store a string value, then assign it a number and it’ll still be valid code and it will execute correctly.

With this in mind, the following code would be perfectly valid in JavaScript:

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:

  • Code becomes less error-prone since you have an extra layer of verification on top of your code that catches simple (yet very common) mistakes.
  • Potential for code optimization, if your compiler (and I’m using that word lightly here, but you can think of transpilers as well) can pick up on better ways to write some sentences based on the types you’re using.
  • Your code is easier to read by others. Not having to mentally parse types is a great help for developers trying to understand code from others.
  • Support for better tooling. With static type declarations, your IDEs can help you write better code by making suggestions or performing checks while you write.

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?

Existing Static Type Checkers for compatible with React

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:

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!):

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:

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.

Is it worth it though?

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.

Conclusion

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!

Otherwise, see you at the next one!

Learn More

--

--

I write about technology, freelancing and more. Check out my FREE newsletter if you’re into Software Development: https://fernandodoglio.substack.com/