A new Javascript static type checker in Flow _ javascript skills

Source: Internet
Author: User
Today we are excited to release the early adopters of Flow, a new Javascript static type checker. Flow adds a static type check for Javascript to improve development efficiency and code quality. This article will share with you a new Javascript static type check tool in Flow, if you are interested, let's learn about it. Today we are excited to release the early adopters of Flow, a new Javascript static type checker. Flow adds a static type check for Javascript to improve development efficiency and code quality. More specifically, static type checks provide benefits such as early error checks, helping you discover some errors that can only be detected at runtime, and Intelligent Code awareness, which will help code maintenance, search, refactoring, and optimization.

We designed all the features of Flow to be built on existing Javascript specifications. Because Flow actively works in the background, the additional compilation overhead is very small. Flow does not require developers to write code-they use a complex set of algorithms to analyze your familiar code style.

Flow is still in its infancy, but we are already using it on Facebook. We hope you can enjoy your use in your own projects and look forward to your feedback. You can access flowtype.org to get started quickly.

Overview

Facebook loves Javascript. It is fast, expressive, and runs everywhere. It is an excellent language for building products. At the same time, developers are troubled by the absence of static types. Bugs are hard to find (for example, the cause of the crash is hidden), and code maintenance is like a nightmare (for example, refactoring is highly risky without knowing all the dependencies ). Flow improves the speed and efficiency, and enables developers to generate Javascript.

Adding a layer of static system on Javascript is not easy. Building blocks in Javascript are extremely expressive. A simple type system cannot accurately combine the expected semantics. To support different Javascript programming paradigms and habits, Flow introduces analysis techniques that are typically used to extract semantics during compilation, such as data-flow and control-flow. Then, the extracted information and advanced type principles are used for type inference. Of course, only one powerful static type analysis is not enough-the Javascript code base will be very large, which requires that the type check must be lightning fast in order not to interrupt the developer's editing-running process. Flow performs analysis by module. All types are limited to the module boundary. This eventually forms a highly parallel and incremental inspection architecture, similar to Hack. This makes the type check response fast, even millions of lines of code.

The Flow type check is optional-you do not need to perform the check all at once. However, the design behind the Flow is based on the assumption that most Javascript code types are implicitly static; although types may not appear everywhere in the code, they exist in the developer's thinking in a form that can be inferred based on the Code correctness. Once possible, Flow will deduce these types, meaning it can detect type errors without modifying the code. On the other hand, some Javascript code in the framework, such as reflection, is widely used, making it very difficult to deduce static types. For this kind of natural dynamic code, the type check will be missed, so Flow provides to add trust to this kind of code and continue. This design is verified by a large number of Javascript code libraries within Facebook: Most code does not pass the Implicit Static type check entries, which allow developers to check for code type errors without adding comments.

This makes the Flow fundamentally different from other Javascript-type systems (such as TypeScript). It is weakened to assume that most JavaScript code is dynamically input and the developer expresses which code should be static. Generally, this kind of design will lead to lower check coverage: fewer types of errors are detected, and the tool is not efficient enough. However, it is reasonable in some cases. Generally, this design cannot provide enough help for actual development without a lot of extra efforts. Even so, Flow allows you to simply obtain this weakened type check, which is very useful for existing code.

To explain the difference, see the following example:

function onlyWorksOnNumbers(x) { return x * 10;}onlyWorksOnNumbers(‘Hello, world!');

Flow can find this error (try to multiply the number and string), but another more conservative analysis needs to explicitly mark the x type. This toy-like example does not seem to be laborious, but almost no one has done it in a giant code library. Flow can detect this error without adding comments-the premise is that the developer wants to do so.

Type System

The Flow type system implements many desired functions. Supports the standard basic types (number, string, boolean). Implicit conversions between types are prohibited except in some special cases. Structure types, such as functions, objects, and arrays, are also supported. The type can be polymorphism.

You may be surprised that the Flow does not regard null and undefined as any of the above types. There are multiple possibilities for these two types, which must be protected by reasonable checks. Other combination types (such as string | number) are also supported. This usage also requires security. Flow knows the impact of dynamic check when narrowing down the type range.

Let's use an example to describe processing null values. The following program always crashes at runtime, but the general type system will think it is okay:

function length(x) {return x.length;}var total = length('Hello') + length(null);

Flow will find this error during compilation and points out that x can be null (The length attribute should not be accessed ). In addition, Flow understands the control Flow of the program, so a simple modification can make the program type correct:

function length(x) { if (x !== null) { return x.length; } else { return 0; }}var total = length('Hello') + length(null);

Flow also understands complex JavaScript Object Models: constructors, methods, prototypes, and dynamic extensions and bindings. It has been tested to support complex types of operations, such as binding objects and extracting keys. We hope that these functions will make it possible to specify a specific type for the framework in the future.

Type errors are usually reported as incompatible definitions with actual values. For example, if function call parameters are insufficient, the object does not contain the attribute to be accessed, or the string is used as a number.

Finally, Flow supports the dynamic type (any), which can bypass the type system check. For example, if any is available, it indicates that static analysis cannot accurately determine the location where an error is reported (usually reflection is used ). In the weak mode, if the above type is not annotated, the Flow is automatically assumed to be any.

Scalability

To expand, Flow checks Each module separately based on the dependencies between the module and other modules and the type interfaces provided by other modules. To generate a type interface, Flow may need to comment on the module boundary.

Flow maintains the semantic information of the entire code base on a persistent server running in the background. At the beginning, Flow analyzes the entire code, then, when a series of file changes (which may be a single file change or a branch switch), the server will incrementally update the modified file and the semantic information of other related files associated with the type. In this way, when developers try to get type errors, they are already on the server, and the response is almost immediate. This server architecture and Hack are built on the same technology.

Compatibility

Flow is committed to supporting the latest JavaScript standards. ES6 features such as destructuring, classes, extended objects, optional function parameters, and core API extensions (such as Map, Set, Promise, and new methods on Object, Array, and Math ). Other features (especially modules) are under development. Flow supports CommonJS/Node. js standard modules.

var Hello = React.createClass ({ render: function() { return 

Hello {this.props.name}

; }});

If the class name you use on JSX is incorrect, Flow will find this problem:

React.render(, ...);

In addition, if you use the React. PropTypes specification in the React class, you can perform a static type check on attributes on JSX:

var Hello = React.createClass ({ propTypes: { name: React.PropTypes.string.isRequired } ...});

Flow will find Attribute missing error, or Attribute type error.

For more details about React support, refer to the document.

Open Source

Most of the Flow code is implemented using OCaml. The code library is being updated and will evolve rapidly in the next few months. In addition to running in Facebook's data code library, we hope the Flow analysis engine can be used to build similar language tools, whether JavaScript or other. Please let us know if you want to join us!

Now, we will introduce all the content of a new Javascript static type checker in Flow, which will be updated in the future. Stay tuned!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.