Static Type Checking  in React

In this post we are going to learn about Static Type Checking in React. Static Type Checking is a process of checking type at compile time whereas in case of dynamic type checking we check for type at run time.

What is static type checking

In the context of React, type checking takes care of making sure your components are receiving the correct data types for their props.

Static type checkers like Flow and TypeScript identify certain types of problems before you even run your code. They can also improve developer workflow by adding features like auto-completion.

React official docs also recommended typescript or flow for a larger code base and proptypes for smaller code base.

Flow

Flow is a static type checker for your JavaScript code. It is developed at Facebook and is often used with React. It lets you annotate the variables, functions, and React components with a special type syntax, and catch mistakes early.

Installation

npm install --save-dev flow-bin

In your pacakge.json add this extra script i.e flow

  "scripts": {
    "flow": "flow"
  }

Create flow config file using below command

npm run flow init

To check for type error run below command

npm run flow

You will get output similar to this

No errors!
✨  Done in 0.17s.

Flow will only checks for the files which includes this annotation at top

// @flow

Example

//@flow

function concat(a: string, b: string) {
  return a + b;
}

let string1: string = "hello"
let string2: number = 42

concat(string1, string2)

if you run flow here you will get error because string2 is of number type but function concat expecting second parameter as string.

Typescript

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.

It is a typed superset of JavaScript, and includes its own compiler. Being a typed language, TypeScript can catch errors and bugs at build time, long before your app goes live.

Installation

npm install --save-dev typescript

In your pacakge.json add this extra script i.e build

 "scripts": {
    "build": "tsc",
  },

You can manually test single file using below command

tcs concat.ts

Example

import * as React from 'react';

const Count: React.FunctionComponent<{
  count: number;
}> = (props) => {
  return <h1>{props.count}</h1>;
};

export default Count;

We can also write same thing using interface

interface Props {
  count: number;
}

const Count: React.FunctionComponent<Props> = (props) => {
  return <h1>{props.count}</h1>;
};

If you want to learn propTypes which is the simplest way to make your code better. You can learn that from here.

Categories: Reactjs