Flow of a new JavaScript static type checker _javascript tips

Source: Internet
Author: User
Tags reflection

Today, we are excited to release a new version of the flow's delicacy, a JavaScript static type checker. Flow adds static type checking for JavaScript to improve development efficiency and code quality. More specifically, the benefits of static type checking, like early error checking, help you find bugs that can only be discovered at runtime, and code IntelliSense, which helps code maintenance, lookup, refactoring, and optimization.

All of the features we design flow are built on existing JavaScript specifications. Because flow proactively works in the background, the extra compilation overhead is small. Flow does not require developers to write code-she uses 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 will be happy to use your project and look forward to your feedback. You can access the flowtype.org quick start.

General overview

Facebook loves JavaScript; it's fast, expressive, and running everywhere, and it's an excellent language for building products. At the same time, there is no static type for developers to worry about. Bugs are hard to spot (for example, the reason for the crash is deep), code maintenance is like a nightmare (for example, it's risky to refactor without knowing all the dependencies). Flow improves speed and efficiency and facilitates developer productivity in using JavaScript.

Adding a layer of static systems above JavaScript is not easy. JavaScript's building Blocks (building block) are highly expressive, and a simple type system does not accurately combine the proper semantics. To support different JavaScript programming paradigms and habits, flow introduces analytical techniques such as data streams (data-flow) and control flows (Control-flow) that are commonly used for compile-time extraction semantics. Then use the extracted information, plus the advanced type principle to do type inference. Of course, just one brute force static type analysis is not enough--javascript the code base is large, which requires type checking to be lightning fast to not interrupt the developer's edit-run process. Flow performs analysis by module and all types are limited to the module boundaries. This eventually forms a highly parallel, incremental inspection architecture, similar to Hack. This makes the type check response fast, even for millions of line-level code.

Type checking of flow is optional-you do not need to perform a one-time check all. However, the design behind the flow is based on the assumption that most JavaScript code types are implicitly static types; Although types may not appear everywhere in the code, they exist in the developer's mind in a form that can be inferred by code correctness. Once possible, flow infers these types, meaning that it can detect type errors without needing to change the code. On the other side, some JavaScript code that exists in the framework, a lot of use of reflection makes static type inference very difficult. For this naturally dynamic code, type checking is riddled with errors, so flow provides you with the added trust and continuation of such code. The design is validated by a large number of JavaScript libraries inside Facebook: Most code does not have an implicit static type check entry that allows developers to check for code type errors without adding comments.

This makes flow fundamentally different from other JavaScript type systems (such as typescript) by weakening the assumption that most JavaScript code is dynamically entered and that the developer itself expresses which code should be statically typed. Typically, this type of design leads to lower check coverage: Fewer type errors are detected and tools are not efficient. However, in some cases it is reasonable that such a design could not provide enough help for actual development without a great deal of extra effort. However, flow allows you to simply get this type of weakening check, which is useful for existing code.

To explain this distinction, consider the following example:

function Onlyworksonnumbers (x) {return
 x *;
}
Onlyworksonnumbers (' Hello, world! ');

Flow can find this error (trying to multiply numbers and strings), while another more conservative analysis requires an explicit annotation of the type of X. In this toy-like example, there is little effort, but there is almost no one in the giant code base. Flow can find this error without adding a comment--of course, if the developer wants to.

Type System

The type system of the flow implements many of the desired functions. Supports standard base types (number, String, Boolean), and implicit conversions between types are prohibited except in special cases. struct types, such as functions, objects, and arrays, are also supported. The type can be polymorphic.

You may be surprised that flow does not treat null and undefined as any of these types. There are many possibilities for both types, and these types must be protected by a reasonable check. Other combination types (such as String | Number) is also supported, and this usage is also required to ensure security. Flow knows the effect of dynamic checking when narrowing the scope of a type.

Let's use an example to describe the processing of null values. The following program always crashes at run time, but the general type system thinks it's fine:

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

Flow will find this error at compile time and indicate that x can be null (the length attribute should not be accessed). In addition, flow understands the control stream of the program, so simple modifications 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 JavaScript's complex object model: constructors, methods, prototypes, and their dynamic extensions and bindings. Has experimented with supporting types of complex operations such as binding objects, extracting keys, and so on. We hope that in the future these features make it possible to specify specific types for the framework.

Type errors are often reported as incompatible with actual values: for example, the parameters of a function call are insufficient, the object does not contain the property to be accessed, or the string is used as a number.

Finally, flow supports dynamic types (any), which can bypass type system checking: For example, any location (usually using reflection) that is not accurately judged by static analysis is available. In addition, flow encounters the above type in weak mode and has no annotation type, and is automatically assumed to be any.

Extensibility

To expand, flow checks each module separately based on the dependencies of modules and other modules and the type interfaces provided by other modules. To generate a type interface, the flow may need to be commented on the module boundary.

Flow maintains the semantic information of the entire code base on a persistent server that runs in the background, and the first flow makes an analysis of the entire code, and then when a series of files changes (possibly a single file change or a branch switch), The server incrementally updates the change file and the semantic information of other related files associated with the type. This way, when a developer tries to get a type error, they are already on the server, and the corresponding is almost immediately. This server architecture is built on the same technology as Hack.

Compatibility

Flow is committed to supporting the latest JavaScript standards. Various 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 modules for commonjs/node.js specifications.

var Hello = React.createclass ({
 render:function () {return
 <div>hello {this.props.name}</div>;
 }
});

If you have an error with the class name you use on the JSX, flow will find the problem:

React.render (, ...);

Also, if you use the React.proptypes specification in react class, you can do a static type check on the attributes on JSX:

var Hello = React.createclass ({
 proptypes: {
 name:React.PropTypes.string.isRequired
 }
 ...
});

Flow will find <Hello/> missing attribute errors, or

More details on supporting react can be found in the documentation.

Open source

Most of the flow code is implemented with OCaml. The code base is actively updated and will evolve rapidly over the next few months. In addition to running within the Facebook-wide data code base, we want the flow's analysis engine to be used to build similar, either JavaScript or other language tools. Please let us know if you want to join!

All right, the whole contents of a new JavaScript static type Checker for flow is first introduced here, follow-up will continue to update, please pay attention!

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.