Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
flow
error checking
annotations

How to add Flow type annotations

Educative Answers Team

Flow type annotations

Flow is an error-checking technology for JavaScript. It is good for checking for errors in variable data types and operations on those variables.

Code

Given that JavaScript does not need explicitly defined data types, Flow also works well without type annotations. However, in certain cases, Type annotations may be useful for limiting variable-type usage in a function.

Take a look below, where a function to sum all the elements of a variable is written.

function sum(array){
  var sum = 0;
  for (x = 0; x < array.length; x++){
    sum = sum + array[x];
  }
  return sum;
}

word = "Educative"
num = [1, 2, 3, 4 ,5]
// Calling with string
console.log(sum(word))
// Calling with array
console.log(sum(num))

This example, which does not use type annotations, will show no error in Flow despite it clearly not being defined for strings. You can see this in how it does nothing to a string other than appending a ‘0’ to its start in a highly inefficient way.

The following example shows the function with type annotations.

function sum(array: number[]){
  var sum = 0;
  for (x = 0; x < array.length; x++){
    sum = sum + array[x];
  }
  return sum;
}

word = "Educative"
num = [1, 2, 3, 4 ,5]
// Calling with string
console.log(sum(word)) // Flow shows error
// Calling with array
console.log(sum(num)) // No error here

While this example cannot be run before a Flow compiler removes the type annotations, it works well to prevent strings from being used where they should not be. Flow will show an error here when the string is passed to the function on line 12. On the other hand, it will not show an error for an array of numbers because the parameter of the function is given the number[] type annotation.

RELATED TAGS

javascript
flow
error checking
annotations
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring