React type checking: what is it? Why you need it?

JavaScript is defined as a “weakly typed” or “untyped” language which means that you don’t have to specify what type of data will be or is declared to a certain variable. It will automatically decide the type based on what value you give this variable. Which is considered smart, because it can figure out what type of data you have and make adjustments so that you don’t have to redefine your different types of data.

Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types
    
let foo = 42; // foo is now a number foo = 'bar'; // foo is now a string foo = true; // foo is now a boolean

What about React?

While JavaScript, being a smart & weakly typed language, is very useful in a lot of cases and intuitive for beginning JS Devs, it is not what your React child components need. When building your React application, the child components have certain expectations on which types of data they need to receive to handle the functionalities that you gave them. Luckily there is a solution: Type checking!

What is type checking?

Type checking makes sure that you are giving the right values to your functionality, while keeping the type errors at a minimum and makink your code easier to read.

Benefits

  • type errors detected at early stage
  • optimised and easier to read code

Now before we go on about type checking you need to know this: there is no right or wrong way in performing type checking correctly. It is all about what your personal preferences are and what works best for you.

In type checking there are two variants: static and dynamic. The main difference between the two is that static type checking happens at compile time, it checks the types before running the application. While dynamic type checking happens at runtime, it checks the types while executing the code. One downside to dynamic type checking is that it results in less optimised code and is more prone to runtime type errors because it forces runtime checks every time the code is executing. Like we said before: which one you choose is based on preference. Now with all this theoretical talk about type checking we all want to know how it is executed in real life and how it looks.

What can we use in our React application for Type checking?

Tools for static type checking

  • Flow
  • TypeScript
  • ...

Flow

Flow checks your code for errors through static type annotations. These types allow you to tell Flow how you want your code to work, and Flow will make sure it does work that way.

Flow is a code linter created by Facebook for easy-to-use type checking in React. It is adaptable and easy to remove or add to your project. The documentation of Flow is really compact but it has just everything what you need to know. To learn more about it, visit the documentation or have a peak at this cheat sheet.

The next simple example is taken directly from the cheat sheet.

    
/* @flow */ function square (n: number) { return n * n } const four = square(2)

TypeScript

TypeScript adds additional syntax to JavaScript to support a tighter integration with your editor. Catch errors early in your editor.

TypeScript is no linter like Flow but a code language developed by Microsoft, to add additional syntax to JavaScript. It provides an extra layer on your JavaScript code to consistently check if your types are correct. It will highlight unexpected behaviour lowering the chances of a bug occurring. To have a deeper knowledge of it we will refer you to the docs.

The relationship between TypeScript (TS) and JavaScript (JS) is rather unique among modern programming languages.

Personally I like this language the most. While in the beginning it is hard to adjust to the strict checking of types, after a lot of messing around you get the hang of it and the outcome is great.

    
const firstStringExample: string = 'This example is of the type string'; const stringExample = (person: string) => { return `Hello, ${person}`; } stringExample('Jane');
    
interface Person { firstName: string; lastName: string; age: number; hasWebsite: boolean; } const objectExample = (person: Person) => { return `Hello, ${person.firstName}`; } objectExample({ firstName: 'Jane', lastName: 'Doe', age: 30, hasWebsite: true });
    
interface Person { firstName: string; lastName: string; age: number; hasWebsite: boolean; } const arrayExample = (persons: Person[]) => { persons.forEach((person: Person, key: number) => { return `Hello, ${person.firstName} - ${person.age}`; }) } const personsArray = [ { firstName: 'Jane', lastName: 'Doe', age: 30, hasWebsite: false }, { firstName: 'John', lastName: 'Doe', age: 30, hasWebsite: false }, { firstName: 'React', lastName: 'Doe', age: 30, hasWebsite: false }, { firstName: 'Flavor', lastName: 'Doe', age: 30, hasWebsite: false }, { firstName: 'Jane', lastName: 'Doe', age: 30, hasWebsite: false }, { firstName: 'Jane', lastName: 'Doe', age: 30, hasWebsite: false }, { firstName: 'Jane', lastName: 'Doe', age: 30, hasWebsite: false }, ]; arrayExample(personsArray);

Tool(s) for dynamic type checking

  • PropTypes

PropTypes

React (and potentially other libraries) will check props passed to your components against those definitions, and warn in development if they don’t match.

React has provided its own build in type checker, for the latest version of React it has moved the PropTypes to a stand alone package. These PropTypes have a range of validators that can be used in checking the props in your React application. When the types don’t match you will get an error or warning in your JavaScript console. For a list of all the exported types you can view the documentation.

Here in Esign we use PropTypes in a lot of our React projects, mainly for Streamic.

    
import PropTypes from 'prop-types'; // your React component code Example.propTypes = { firstName: PropTypes.string; lastName: PropTypes.string; age: PropTypes.number; hasWebsite: PropTypes.bool; };

Recap

Type checking is a useful method for working more functionally and making fewer variable type errors. There are many ways of doing type checking, and there is no right or wrong method. In the end, there are only two things that matter: your personal preferences and the end result.