Static Type Checking

Introduction

The phrase type checking might sound familiar to you. You've probably heard terminology like statically-typed or dynamically-typed when referring to a specific language.

The type system and data types are critical components of every programming language.

 

This article will go through the basics of type checking and explore Static type checking in JavaScript in detail.

Type Systems

A type defines a collection of potential values as well as a set of actions or operations that a variable may do. There is a type for every item. Variables in a strictly typed programming language like C++ or Java are declared as being of a specific type, limiting the variable's contents to just that type's values.

 

Languages like Python, JavaScript, on the other hand, are dynamically typed languages.

It's possible to have a variable in JavaScript that started as a string and has evolved into a reference to an object much later in its lifespan.

Type Checking

The notion of types is meaningless unless there is a method in place to ensure that those kinds make logical sense in the program and that it can be run properly. Here's when type checking comes in handy.

 

Type checking validates and enforces constraints on the type of a variable with the goal of minimizing type mistakes. Because type errors can occur while the program is executing, type checking assures that it is type-safe.

 

When a program is deemed to be not type-safe, there is no one standard sequence of action that occurs when a type error occurs. Irrespective of the outcome, the process of type checking is required. 

 

Static type checking and dynamic type checking are the two main types of type checking.

 

Now that we've covered the fundamentals of what types are and how type checking works, we'll dig into the first of the two methods of type checking: Static type checking.

Static Type Checking: What does it mean?

Static typing, which is used in languages like Java, C, and C++, is thought to be a risk-averse approach to coding since type checking happens at compile time. To put it simply, the goal of static type checking is to detect and reject programs that may produce an error if they are run. 

 

Static typing typically results in compiled code that executes faster because the compiler can create optimized machine code when it knows the specific data types that are in use.

Static Type Checking and JavaScript

The idea of static type checking for JavaScript might sound conflicting because the language is dynamically typed by definition. 

 

Naturally, the following question arises: Why would you bother adding static type checking to a language meant to function without it?

Let's go through an example to comprehend this situation better.

 

function curiosity(a

{
  if(a) 

  {
    return true;
  }  
  a = a*7;
  return a;
}

 

The above code is completely valid in JavaScript and yet you can’t tell the return type of the function curiosity or the type of variable a.

 

To avoid such scenarios, you might consider adding Static type checking even in a language that is dynamically typed.

Static Type Checkers for JavaScript

Although the notion of having a static type checker for this language may sound appealing, the actual work necessary to accomplish so appears to have thwarted most efforts.

Keeping this in mind, Flow and TypeScript have emerged as the two primary solutions for enabling static type checking in the JavaScript community.

 

While Flow and TypeScript integrate into your development process in somewhat different ways, they have many parallels in terms of syntax and have the same aims.

Flow

Developed at Facebook, Flow is easy to set up in an existing codebase. Flow enables you to add type annotations to your Vanilla JavaScript and then process that code to detect errors.

Installations & Adding Flow

Run the following code to install Flow

npm install --save-dev flow-bin

 

To use this from the terminal, add flow to the "scripts" section of your package.json like this:

{
  // ...
  "scripts": {
    "flow""flow",
    // ...
  },
  // ...
}

 

You will need to strip away the added annotations so that your code can be correctly interpreted, for this install its type remover by writing:

npm install --save-dev flow-remove-types


Note: If you used Create React App to create your project, the Flow annotations are already stripped by default.

Running Flow

After following the above steps, to run Flow, type in the following code:

npm run flow

Adding annotations

Flow checks just the files that have this annotation by default:

// @flow

It is usually placed at the top of a file.

 

There is also the option to make Flow check all files independent of annotation. It is appropriate for a new project if you wish to write it using Flow entirely.

Now, you're ready to use Flow in your project!

TypeScript

Developed by Microsoft, TypeScript is a typed superset of JavaScript that comes with its own compiler. As TypeScript is a typed language, it may detect flaws and issues during the build process long before your project goes live.

Create React App

Create React App has TypeScript support out of the box. To begin a new Create React App project with TypeScript, type:

npx create-react-app my-app --template typescript

 

Or, to add it to an existing Create React App, first install using:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

Next, rename any file to be a TypeScript file (e.g., source/index.js to source/index.tsx) and then restart your development server.

Manual

Because of the language's nature, you'll need to install a transpiler, which will transform your TypeScript code into JavaScript when you're ready to test it.

npm install -g typescript

 

To check your code and transpile it, you will type the following:

tcs name-of-your-file-here.ts

The .ts extension specifies which files TypeScript has to analyze.

Unlike Flow, there is no need to add annotations here.

Frequently Asked Questions

  1. What is the key difference between static type checking and dynamic type checking?
    The primary distinction between the two is that the type of variable is known at compile time with static type checking, whereas the type of variable is known at runtime with dynamic type checking.

     
  2. When to use static type checking?
    Static type checking is often well suited for developing and maintaining systems that do not change frequently, execute relatively simple procedures, and rely largely on operational consistency.

Key Takeaways

This article covered static type checking and a few ways to implement it in JavaScript. Although implementing static typing requires extra effort, it adds certain benefits too. Ultimately it all boils down to personal choices.

 

So this was all about static type checking. If you want to learn advanced front end web development, Coding Ninjas has one of the best courses available, which you can find here.

 

Thank you for reading!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think