Flow.js
Created|Updated
|Word count:1.1k|Reading time:4min|Post View:
Flow
参考文献:https://www.cnblogs.com/zhuzhenwei918/p/7150762.html
最全的手册:https://www.saltycrane.com/cheat-sheets/flow-type/latest/#builtins
Flow.js是FaceBook发布的开源Javascript静态类型检查器。他给JavaScript提供了静态类型来提高开发人员的生产力和代码质量。
初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| yarn init --yes
yarn add flow-bin --dev
yarn flow init
yarn flow start
yarn flow
yarn flow stop
yarn flow check
|
类型标注
1 2 3 4 5 6 7
|
function square(n: number): number { return n * n; } square("2");
|
完成编码过后自动移除类型注解
方法一
1 2 3 4
| yarn add flow-remove-types --dev
yarn flow-remove-types . -d dist
|
方法二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| yarn add @babel/core @babel/cli @babel/preset-flow -dev
{ "presets":["@babel/preset-flow"] }
yarn babel src -d dist
|
语法
基础变量
1 2 3 4 5 6
| const a: string = 'Hey' const b: number = 100 const c: boolean = true const d: null = null const e: void = undefined const f: symbol = Symbol()
|
数组类型限制
1 2 3 4 5 6 7
| const arr: Array<number> = [1,2,3]
const arr1: number[] = [1,2,3]
const foo: [string,number] = [1,2,3]
|
对象类型限制
1 2 3 4 5 6 7 8 9 10 11 12 13
| const obj1: { foo: string, bar: number } = { foo: 'string', bar: 100 }
const obj2: { foo?: string, bar: number } = { bar: 100 }
const obj3 = {} obj3.key1 = 'value1'
const obj3: { [number]: number} = {} obj3.key1 = 100
|
函数类型限制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| function sum (a:number,b:number){ return a*b }
function foo():number{ return (typeof number) }
function foo(): void{ return (typeof undefined) }
function foo(callback:(string,number) => void){ callback('who am i', 42) }
foo(function(str,n){ `不可有返回值` })
|
特殊类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| `字面量类型`
const a: 'Hey' = 'Hey'
const b: 'Hey' | 'Hello' | 'Hi' = 'Hello'
const c: string | number = 'string' const d: StringOrNumber = string | number
`meybe`
const gender: ?number = undefined
const gender: number | void | null = undefined
`mixed与any`
function passMixed(value: mixed | any){ passMixde('可以是所有类型如:string number') }
function passAny(value: mixed){ value.substr(1) value. * value } PassAny('string'); PassAny(100);
function passMixed(value: mixed){ if(typeof value === 'string' ){ value.substr(1) } } PassMixed('string')
|
环境API
1 2 3 4 5 6 7 8 9
| 如: const element:HTMLElement | null = document.getElementById('app')
https: https: https: https: https:
|