npm init -y -> cnpm i flow-bin -D
"flow": "flow"
npm run flow init
//@flow
function sum(a:number, b:number) {
return a+b
}
sum(100, 100)
sum('100', '100')
项目中移除类型检查
a.安装命令:npm install --save-dev flow-remove-types
b.package.json中修改配置:
# 把目录文件编译之后转到dist目录下
"scripts": {
"flow": "flow",
"flowRemove": "flow-remove-types src -d dist/"
}
c.运行: npm run flowRemove
首先安装@babel/core,@babel/cli 并@babel/preset-flow 使用
a.安装命令:npm install --save-dev @babel/core @babel/cli @babel/preset-flow
b.在根目录创建.babelrc文件:
{
"presets": ["@babel/preset-flow"]
}
c.package.json文件中添加
"build": "babel ./src -d ./dist"
d.npm run build
/**
* 变量类型注解
*/
let num: number = 100;
num = "string"
/**
* 函数返回值类型注解
*/
function foo():number{
return '100'
}
function test():void {
}
1、原始类型
/**
* 原始类型
*/
//@flow
const a: string = "100";
const b: number = Infinity;
const c: boolean = false;
const d: null = null;
const e: void = undefined; // undefined类型
const f:symbol = Symbol()
2、数组类型
/**
* 数组类型
*/
const arr1: Array<number> = [1, 2, 3]
const arr2: number[] = [1, 2, 3]
//元组
const foo: [string, number] = ['foo', 100]
3、对象类型
const obj1: { foo: string, bar: number } = { foo: 'name', bar: 100 }
const obj2: { foo?: string, bar: number } = { bar: 100 } //对象属性可选
const obj3: { [string]: string } = {}
obj3.key1 = 'value1'
obj3.key2 = 'value2'
4、函数类型
function test(a: number) {
}
function test1():number {
return 100
}
function myFun(callback:(string, number) => void){
callback('name',100)
}
myFun(function (str, n) {
console.log(str)
})
5、特殊类型
//字面量类型
const a: 'foo' = 'foo'
const type: 'success' | 'warning' | 'danger' = 'danger'
const b: string | number = 'aaaa' //100
type StringOrNumber = string | number //给类型做别名
const c: StringOrNumber = 'name'
//----------------------
const gender: ?number = undefined //除了接收number之外 还可以接收null或undefined
const gender: number | null |void = undefined
6、 Mixed any
function passMixed(value: mixed) { //强类型,需用type判断类型
if (typeof value == 'string') {
value.substr(1)
}
if (typeof value == 'number') {
value * value
}
}
passMixed('string')
passMixed(100)
function passAny(value: any) { //弱类型,兼容以前代码
value.substr(1)
value*value
}
passAny('string')
passAny(100)
7、 运行环境内置api
const element: HTMLElement | null = document.getElementById('app')