qyfeng03
在文件中开启flow检查
// @flow
什么都不做,就可以有一些自动推断功能
// @flow
function square(n) {
return n * n;
}
square("2");// Error!
手动配置类型
// @flow
function square(n: number): number {
return n * n;
}
square("2"); // Error!
非必选
// @flow
function foo(x: ?number): string {
if (x) {
return x;
}
return "default string";
}
多选类型
function testFlow(param: string | number){
return param
}
testFlow('1') // 11
testFlow(1) // 2
testFlow([]) // Error!
枚举类型
function testFlow(param: 1 | 2 | 3){
return param
}
testFlow(1)
testFlow(2)
testFlow(4) // Error!
任意类型
function testFlow(param: any){
...
}
变量类型
const bar: number = 2;
对象类型
var obj1: { foo: boolean } = { foo: true };
数组类型
let arr2: (?number)[] = [1, 2]; // Works!
返回值
function testFlow(param: number):string{
return param + param // Error!
}
箭头函数
let method = (str: string, bool?: boolean, ...nums: Array<number>): void => {
// ...
};
类型别名
// @flow
type MyObject = {
foo: number,
bar: boolean,
baz: string,
};
function method(val: MyObject) { /* ... */ }
范型
function testFlow<T>(value: T): T {
return value;
}
const stringVar:string = testFlow('123')
const numberVar:number = testFlow(123)
const numberVar2:number = testFlow('123') // Error
类对象(Flow不推荐函数构造对象)
function testFlow(value: People) {
console.log(value.name)
}
class People{
name: string // 必须声明
constructor(name){
this.name = name
}
}
testFlow(new People('qe'))
接口(感觉完全就是在写Java)
interface Dog {
name: string;
bark(value: string):any;
}
class MyDog implements Dog{
name:string;
constructor(name){
this.name = name
}
bark(value:string):any{
console.log('bark:'+value)
}
}
const dog:Dog = new MyDog('flappy')
导入导出Flow类型(必须导入导出文件都开启flow)
// @flow
export default class Foo {};
export type MyObject = { /* ... */ };
export interface MyInterface { /* ... */ };
// @flow
import type Foo, {MyObject, MyInterface} from './exports';