yarn init -y
安装 flow-bin 模块: yarn add flow-bin -D
创建配置项 yarn flow init
==> .flowconfig
类型检查 类型注解 1 2 3 4 5 6 function sum (a : number, b : number) { return a + b } sum (1 , 2 )sum ('12' , '34' )
yarn flow
进行检查
flow-remove-types 移除注解
flow 仅用于编码时找出错误,编码完成后需移除注解
安装 yarn add flow-remove-types -D
运行 yarn flow-remove-types src -d dist
src
表示当前文件所在目录
-d
指定输出目录 如 dist
1 2 3 4 5 6 7 8 function sum (a , b ) { return a + b } sum (1 , 2 )sum ('12' , '34' )
babel 移除注解 $ yarn add @babel/core @babel/cli @babel/preset-flow -D
创建 .babelrc
1 2 3 { "presets" : ["@babel/preset-flow" ] }
运行yarn babel src -d dist
结果
1 2 3 4 5 6 function sum (a, b ) { return a + b; } sum (1 , 2 );sum ('12' , '34' );
各种类型 原始类型 1 2 3 4 5 6 7 const a : string = 'string' const b : number = 100 || NaN || Infinity const c : boolean = false || true const d : null = null const e : void = undefined const f : symbol = Symbol ()
数组 1 2 3 4 5 6 7 const arr1 : Array <number> = [1 , 2 , 3 ]const arr2 : number[] = [1 , 2 , 3 ]const foo : [string, number] = ['foo' , 100 ]
对象 1 2 3 4 5 6 7 8 9 10 11 const obj1 : { str : string, num : number} = { str : 'string' , num : 100 }const obj2 : { str?: string, num : number} = { num : 100 }const obj3 : { [string]: string } = {}obj3.key1 = 'string'
函数 1 2 3 4 5 6 7 8 function fn (callback : (string, number ) => void ) { callback ('string' , 100 ) } fn (function (str, num ) { return undefined })
特殊类型 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 const aaa : 'aaa' = 'aaa' const type : 'success' | 'warning' | 'danger' = 'success' type StringOrString = string | number const bbb : StringOrString = 'string' const gender : ?number = null function passMixed (value : mixed) { if (typeof value === 'string' ) { value.substr (1 ) } } passMixed ('string' )passMixed (100 )function passAny (value : any) { value.substr (1 ) value * 10 } passAny ('string' )passAny (100 )
运行环境 1 2 const ele :HTMLElement | null = document .getElementById ('app' )