Typing in JavaScript — Flow vs. TypeScript

There are two typed extensions of JavaScript, Microsoft’s TypeScript and Facebook’s Flow. In this article, we’ll look at and compare the features of each of these.

At Sulu we have decided to use Flow for static type checking, and I am still convinced that it was the correct decision back then. However, today TypeScript seems to be the much more popular choice. This claim can also be supported by earlier blog posts and presentations being more about what to choose, whereby more recent ones are about how to switch. So I think it is time to reconsider that decision, therefore I am going to compare these type checkers in this blog post.

#@ What is static type checking?

Static type checking has the goal of finding errors before you even run your code. This will catch quite a bunch of errors for you, and helps a lot to deliver higher quality code. Let’s have a look at a short example:

console.log(5/"5");

This code is syntactically correct, so JavaScript will not complain about this, until it executes that line of code. Since it is pretty obvious that you cannot divide a number by a string, you might say you are not doing that anyway, but imagine that the value of "5" is stored in a variable, and the value of that variable is not completely clear, because it is determined in a 100 lines of code. In that case it would be quite easy to mess this up in some way, without immediately realizing it. A static type checker would tell you about the error at the moment you introduce it, and you are much more likely to know what’s wrong than when finding out about this error at runtime a year later.

Now there are different ways on how to apply static type checking. Many compiled languages do this during their compilation step, which means that the program does not compile at all if you get any type errors in your project. This is a valid approach, and you will also know about the error very soon. But you are losing the opportunity to quickly test doing something in a slightly different way, because you might have to adjust a huge amount of types before you can even compile the program.

JavaScript is not a compiled language, therefore it can only check the code when it is being interpreted, i.e. at runtime. And that’s exactly where TypeScript and Flow jumps in: These are tools that allow to annotate your JavaScript code with type annotations and check based on top of them if everything can work as expected. However, you are not writing pure JavaScript anymore, but instead you have to somehow turn that into pure JavaScript in order for browsers to understand your code. TypeScript comes with its own compiler for that, whereby Flow just relies on Babel to get rid of the annotations for you. TypeScript needs that compilation step for certain features it implements, because strictly speaking it is more than just a static type checker.

The advantage of the latter approach is that you can adjust the code in a way that types will fail, but you can ignore that for the moment, if you are just trying to quickly test something. In a compiled language you would have to fix all the type errors first. Now you can say that the program won’t run anyway as expected (although that is not completely true, because you might use it in a way that the type errors don’t matter), but at least it can run until a certain point, where you might be able to already do a console.log to check on something. That’s something I really enjoy.

On a sidenote, there are also languages like PHP, which have improved their type system over the last years significantly, but it still feels a bit weird. PHP comes with the possibility to annotate your code with types in many different places, but it does not allow to check these errors before runtime. So you can e.g. define in a function that the parameter must be a string, but if you are calling the function with a wrong type, you will not realize that before this code is being executed, in which case you will get a runtime error. In my opinion this is the worst of both worlds, because you can’t tell about the errors before actually running the code, and it doesn’t allow you to quickly test something with different types. To be fair, there are tools like PHPStan and Psalm that work in a similar fashion than TypeScript and Flow, but PHP will still not allow to execute your code with wrong types.

#flow #javascript #typescript #web-development #developer

What is GEEK

Buddha Community

Typing in JavaScript — Flow vs. TypeScript

Typing in JavaScript — Flow vs. TypeScript

There are two typed extensions of JavaScript, Microsoft’s TypeScript and Facebook’s Flow. In this article, we’ll look at and compare the features of each of these.

At Sulu we have decided to use Flow for static type checking, and I am still convinced that it was the correct decision back then. However, today TypeScript seems to be the much more popular choice. This claim can also be supported by earlier blog posts and presentations being more about what to choose, whereby more recent ones are about how to switch. So I think it is time to reconsider that decision, therefore I am going to compare these type checkers in this blog post.

#@ What is static type checking?

Static type checking has the goal of finding errors before you even run your code. This will catch quite a bunch of errors for you, and helps a lot to deliver higher quality code. Let’s have a look at a short example:

console.log(5/"5");

This code is syntactically correct, so JavaScript will not complain about this, until it executes that line of code. Since it is pretty obvious that you cannot divide a number by a string, you might say you are not doing that anyway, but imagine that the value of "5" is stored in a variable, and the value of that variable is not completely clear, because it is determined in a 100 lines of code. In that case it would be quite easy to mess this up in some way, without immediately realizing it. A static type checker would tell you about the error at the moment you introduce it, and you are much more likely to know what’s wrong than when finding out about this error at runtime a year later.

Now there are different ways on how to apply static type checking. Many compiled languages do this during their compilation step, which means that the program does not compile at all if you get any type errors in your project. This is a valid approach, and you will also know about the error very soon. But you are losing the opportunity to quickly test doing something in a slightly different way, because you might have to adjust a huge amount of types before you can even compile the program.

JavaScript is not a compiled language, therefore it can only check the code when it is being interpreted, i.e. at runtime. And that’s exactly where TypeScript and Flow jumps in: These are tools that allow to annotate your JavaScript code with type annotations and check based on top of them if everything can work as expected. However, you are not writing pure JavaScript anymore, but instead you have to somehow turn that into pure JavaScript in order for browsers to understand your code. TypeScript comes with its own compiler for that, whereby Flow just relies on Babel to get rid of the annotations for you. TypeScript needs that compilation step for certain features it implements, because strictly speaking it is more than just a static type checker.

The advantage of the latter approach is that you can adjust the code in a way that types will fail, but you can ignore that for the moment, if you are just trying to quickly test something. In a compiled language you would have to fix all the type errors first. Now you can say that the program won’t run anyway as expected (although that is not completely true, because you might use it in a way that the type errors don’t matter), but at least it can run until a certain point, where you might be able to already do a console.log to check on something. That’s something I really enjoy.

On a sidenote, there are also languages like PHP, which have improved their type system over the last years significantly, but it still feels a bit weird. PHP comes with the possibility to annotate your code with types in many different places, but it does not allow to check these errors before runtime. So you can e.g. define in a function that the parameter must be a string, but if you are calling the function with a wrong type, you will not realize that before this code is being executed, in which case you will get a runtime error. In my opinion this is the worst of both worlds, because you can’t tell about the errors before actually running the code, and it doesn’t allow you to quickly test something with different types. To be fair, there are tools like PHPStan and Psalm that work in a similar fashion than TypeScript and Flow, but PHP will still not allow to execute your code with wrong types.

#flow #javascript #typescript #web-development #developer

TypeScript VS Flow: Type Checking Front End JavaScript

#react #typescript #javascript #reactjs #flow

Fancorico  Hunt

Fancorico Hunt

1590548916

TypeScript vs. Flow: Type Checking Front End JavaScript

Lots of things about development and code comes down to preferences, but when it comes to type checker for JavaScript, it’s hard to pick Flow over TypeScript.

Although both are backed by a big tech company and have similar type checking syntax, TypeScript has great support from popular JavaScript frameworks and has a clear development roadmap so that you know what to expect in the future.

#javascript #typescript #flow

Toby Rogers

Toby Rogers

1582273702

TypeScript vs. Flow - What is the Difference?

JavaScript is a dynamically typed language. This means that data types of variables can change as we assign different values to them.

There’s no built-in way to annotate or restrict the types of variables. Therefore, we need to write our programs in another language and then transpile it to JavaScript if we want that capability. We need a language that’s a typed extension of JavaScript to check and restrict the types of our variables.

There are two typed extensions of JavaScript, Microsoft’s TypeScript and Facebook’s Flow. In this article, we’ll look at and compare the features of each of these.

TypeScript vs. Flow

Developer experience

The developer experience can be measured using various scenarios, including support by various libraries and frameworks, ease of use, and overall productivity. The full documentation of TypeScript can be found here and the full documentation for Flow can be found here.

From the support perspective, TypeScript is much better because major frontend frameworks like Vue, Angular, and Facebook’s own React all support TypeScript out of the box. For example, we can build a Vue project with TypeScript by choosing the TypeScript option from the Vue CLI.

Once we chose TypeScript, then we can configure it to transpile to JavaScript, (usually ES5) to maximize the support of browsers.

Then when we reference Vue when creating our component we’ll get TypeScript type inference:

import Vue from 'vue'

const Component = Vue.extend({
  // ...
})

Also, with Vue, we can write components with TypeScript in its own special way with classes like this:

<template>
  <button @click="onClick">Click!</button>
</template>


<script lang="ts">
import * as Vue from "vue";
import { Component } from "vue-property-decorator";

@Component()
class App extends Vue {
  public message: string = "Hello World";

  public onClick(): void {
    window.alert(this.message);
  }
}

export default App;
</script>

We can see the familiar JavaScript syntax with some TypeScript annotations. For example, Angular is built with TypeScript and it uses TypeScript almost exclusively. There was an option to write Angular apps with plain JavaScript but it never caught on.

On the other hand, Flow is only supported by React. According to this document, we can use Flow with React, we just have to add Flow support in the Babel configuration to enable support for Flow with Babel.

To add Flow support, we just run:

npm install --save-dev @babel/preset-flow

and add:

{
  "presets": ["@babel/preset-flow"]
}

to the .babelrc file.

The syntax differences between Flow and TypeScript isn’t significant. They both support similar types like the usual JavaScript data types, literal types, union types, conditional types, etc. Also, both TypeScript and Flow use similar syntax for type annotations.

Both TypeScript and Flow have operators and various utility types to preserve the flexibility of the JavaScript type system. For instance, the following is the same in both Flow and TypeScript:

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

The function above takes two strings and then returns both concatenated together. They both have types for optional properties. TypeScript has the nullable type and Flow has the maybe type. Both Flow and TypeScript have generics, which we can use to write code that takes a variable type.

For instance, the following function takes whatever is passed in and returns the same thing:

function identity<T>(value: T): T {
  return value;
}

We can use it by writing:

identity<string>('foo')

Flow provides typecasting as does TypeScript. They work similarly. With Flow, we can cast a value to a related type by using the : symbol like this:

let value = 1;
(value: number);

The code above is Flow code to cast a value type 1 to a number.

With TypeScript, we can cast types using the as operator like this:

let value = 1 as number;

Another important feature that both Flow and TypeScript have are interfaces. Interfaces are used as types that restrict the structure of an object.

interface PersonInterface {
  firstName: string;
  lastName: string;
  fullName(firstName: string, lastName: string): string
}

This is code for an interface in both Flow and TypeScript. Then we can create objects and classes that implement the interface with the implements keyword in both Flow and TypeScript.

interface PersonInterface {
  firstName: string;
  lastName: string;
  fullName(firstName: string, lastName: string): string
}

class Person implements PersonInterface {
    firstName: string;
    lastName: string;
    constructor(firstName: string, lastName: string){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    fullName(firstName: string, lastName: string): string {
        return `${firstName} ${lastName}`;
    }
}

The code above creates a class that implements the PersonInterface interface.

We’ll get an error with the Flow and TypeScript transpilers if we didn’t implement all the members listed in the interface.

One unique feature of Flow is that we can put our type checking code in the comments. For example, we can add comments for type checking like this:

function greet(greeting /*: string*/) /* : string */ {
  return greeting;
}

This isn’t available with TypeScript. However, this isn’t a big draw since comments don’t have autocomplete or syntax highlighting.

TypeScript has much better support with text editors. Editors like Visual Studio Code and IDEs like WebStorm have built-in support for TypeScript. As we can see from JetBrain’s website, WebStorm has built-in support for debugging TypeScript code and also checking it for errors. Syntax and compilation errors are displayed right in the IDE. Hints are available as we’re typing in code in WebStorm. Type checking with TypeScript is built into these programs.

Supporting TypeScript means that developers get full type checking, auto-complete, and compiler errors right on the screen of your editor even before building the code. TypeScript code has type definitions that are added to libraries to denote the types that the code has.

It also has a language server to check for these types. Flow checks types locally and doesn’t have a language server or type definitions like TypeScript. We need to run the Flow compiler to check our app, whereas we can check our JavaScript code with a TypeScript language server as we’re typing code into our files.

Type definitions are bundled with libraries like Lodash and moment.js so that we get autocomplete and type checking support in text editors that work with TypeScript like Visual Studio Code.

Developer experience comparison

TypeScript vs. Flow

Efficiency

The performance difference between Flow and TypeScript is minimal. TypeScript consistently uses 500 to 600 MB of RAM and Flow isn’t too different. There isn’t much difference between them in terms of computing resource efficiency.

Community support

Community support for TypeScript is much better than Flow, as we have already mentioned. Other than React, Flow’s support is sparse. Most libraries don’t support Flow.

Also, there’s little documentation outside of the official sources, and in Stack Overflow, there aren’t too many questions about Flow when compared to TypeScript.

As we can see from https://stackoverflow.com/questions/tagged/typescript, there are more than 100,000 questions for TypeScript and from https://stackoverflow.com/questions/tagged/flow we only see a few hundred questions, and most of them have nothing to do with Facebook’s Flow. For instance, there’s also documentation for adding Flow support to a Create React App project.

Also, for plain JavaScript projects, there is documentation to install Flow support in an existing project via Babel. Many frameworks have support for TypeScript, including Vue, Angular, and React frontend frameworks as we saw above. Also, Node.js web frameworks like Express can have TypeScript support added. Nest.js is a backend framework that’s built with TypeScript support baked in, allowing us to use TypeScript for development without making big changes to our project.

For example, with Express, we just have to run:

npm install --save-dev typescript

to install the TypeScript transpiler.

Then we can add a tsconfig.json file to configure our TypeScript transpiler by writing something like:

{
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es6",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*"
            ]
        }
    },
    "include": [
        "src/**/*"
    ]
}

Then to install the type definitions for Express and Node’s standard library, we run:

npm install --save-dev @types/node @types/express

As we can see, it’s not too hard to use TypeScript with existing libraries since there are TypeScript type definitions for many libraries and frameworks.

For more type definitions for TypeScript, we can go to the DefinitelyTyped website.

As we mentioned in the developer experience section, editor support is way better with TypeScript. Visual Studio Code, Sublime, and other editors have support for TypeScript either built-in as with Visual Studio Code or available as a plug-in for Sublime.

Resources and documentation quality

TypeScript definitely wins in terms of the quantity, resources, and documentation available.

Since it’s supported by many libraries and frameworks, lots of people are using TypeScript daily. There is plenty of information about each feature in TypeScript, including examples and explanations.

Here are a few more resources

TypeScript playground supports different versions of TypeScript so we can see how our code acts with different versions of the TypeScript transpiler.

On the other hand, Flow only has some documentation and a short document on how to set up Flow with React.

Conclusion

TypeScript is definitely the more widely used language that’s transpiled to JavaScript. TypeScript has more support than Flow does with libraries, frameworks, and it’s used more pervasively in apps because of that. They both provide very similar type checking abilities which retain the flexibility of JavaScript.

TypeScript and Flow both include all the built-in JavaScript data types. In addition, we can use it to define literal types, union types, intersection types, etc. to create more flexible types.

In addition, they both have interfaces to restrict the members that we can add to objects when they’re used to annotate the type of an object. For creating scalable JavaScript code, TypeScript is definitely the winner since no other alternatives have such pervasive usage and support.

#javascript #typescript #flow #web-development

Samanta  Moore

Samanta Moore

1624959720

Java Vs. JavaScript: Know the Difference

What a mess it could be to share the same name — especially if you are a programming language. Even if you are already over 20 years old, IT newbies periodically confuse you with your namesake. This happens all the time with Java and JavaScript, although they are not related at all! As someone on the internet said. They correlate in much the same way as a car and a carpet.

Why do these two languages have such similar names? How do they differ from each other, and what else do they have in common? This article will provide the answers to these questions.

In the Beginning, It Was Java

The Same Year, A Little Bit Later: Meet JavaScript!

Technical Differences Between Java and JavaScript

What Can You Build in Java and JavaScript?

#java #javascript #javascript-development #java-development #learn-to-code-java #learn-javascript #programming #java-vs-javascript