刘菁
孙菁
REA Media
Flow is a JavaScript static type checker built by
14000+ stars on
Main features:
var obj = {
data: {
getListingData: function(){};
},
map: "some map",
.
.
.
};
function func(obj) {
obj.data.getListingData();
};
//某文件
function hasHeadingText(obj) {
return obj.hasHeadingText === true;
}
//某处
var obj = {'hasHeadingText' : 'true'}
function insertHeadingText() {
if(hasHeadintText(obj)) {
//insert headint text
}
}
yarn add --dev babel-cli babel-preset-flow
{
"presets": ["flow"]
}
yarn add --dev flow-bin
flow init
// @flow
/* @flow */
yarn run flow
yarn run flow stop
// @flow
function concat(a: string, b: string) {
return a + b;
}
concat("A", "B"); // Works!
concat(1, 2); // Error!
function getColor(name: "success" | "danger") {
switch (name) {
case "success" : return "green";
case "danger" : return "red";
}
}
getColor("success"); // Works!
getColor("danger"); // Works!
// $ExpectError
getColor("error"); // Error!
function acceptsMaybeNumber(value: ?number) {
// ...
}
acceptsMaybeNumber(42); // Works!
acceptsMaybeNumber(); // Works!
acceptsMaybeNumber(null); //works
Arrays
// ?Type[] is the equivalent of ?Array<T>
// @flow
let arr1: ?number[] = null; // Works!
let arr2: ?number[] = [1, 2]; // Works!
let arr3: ?number[] = [null]; // Error!
Functions
// @flow
function concat(a: string, b: string): string {
return a + b;
}
concat("foo", "bar"); // Works!
// $ExpectError
concat(true, false); // Error!
Type Alias
// @flow
type MyObject = {
foo: number,
bar: boolean,
baz: string,
};
var val: MyObject = {
foo: 1,
bar: true,
baz: 'three',
};
Class
// @flow
class MyClass {
prop: number;
method() {
this.prop = 42;
// $ExpectError
this.data = "blala"; // Error!
}
}
React
import * as React from 'react';
type Props = {
foo: number,
bar?: string,
};
function MyComponent(props: Props) {
props.doesNotExist;
// Error! You did not define a `doesNotExist` prop.
return <div>{props.bar}</div>;
}
<MyComponent foo={42} />
Type checker +
A Complier that emits plain JavaScript
Angular Community
Type checker
Rely on Babel or other tools to remove type annotation
React Community
Hey we’d like to use this library to improve code quality on your project
vs
We’d like to write the code for your project in a language your internal team doesn’t know.