类型安全角度: 实参 和 行参 是否需要类型相同
弱类型: 可以随意隐式转换 (运行阶段报错)代码层面
强类型 : 不可随意隐式转换,(编译阶段报错)语法层面
类型检查角度
静态语言类型:变量声明时类型就明确,且不可变
动态语言类型: 运行阶段才能明确类型,类型随时可变
总结: 变量没有类型, 变量中的值时有类型的 (变量是个空盒子),薛定谔的🐱?
强类型的优势总结:
- 更早暴露错误
- 代码更智能,准确
- 重构更牢靠
- 减少不必要的类型判断
Flow- depency
类型注解 , 变量, 函数返回值类型 参数类型
Valuename: number = 5
通过babel 或者flow 的官方模块 在编译前自动去除
flow 依赖 3 点 必备
- install depency
- //@flow
- Valuename: number = 5
// @flow
let num: number = 100
function foo (): number { // indicate the return value is a number
return 'string' // error
}
function foo (): void { // 无返回值函数标记为void
// some code
}
// @flow
// 原始数据类型 6
const a: string = 'string'
const b: number = 100 // NaN // infinity (可以存放NaN)
const c: boolean = true // false
const d: null = null
const e: void = undefined
const f: symbol = symbol()
// 数据结构 - array
const arr1: Array<number> = [1,2,3]
const arr2: number[] = [1,2,3]
//元组: 固定长度的数组
const arr3: [string, number] = ['guohai',10] //限制长度以及第一第二位的类型
// 数据结构 - object
const obj1:{foo: string, bar:number} = {foo: 'string', bar:100} // 限制key 和数据类型
const obj2:{foo?:string, bar:number} = {bar:100} //可选key
const obj3:{[string]:string} ={} // 允许添加任意个数的key, 限定key 和value 为 string
//函数的类型限制
function foo (callback:(string, number) => void) { // 限制 参数 + 返回值 类型
callback('string', 100)
}
//字面量类型
// 限制变量必须是某一个值, 限制value
const fxx:'foo' = 'foo'
const type:'success'|'warning'|'danger' = 'success'
const b: string|number = 100 // '100'
type StringOrNumber = string|number
const b: StringOrNumber = 100 // '100'
// Maybe 类型 // 在基础上允许添加 null 和 undefined 类型
const gender: ?number = 100 // null // undefined
const gender: number|null|undefined = 100 // null // undefined
Flow Mixed(强类型) Any(弱类型)
function passMixd (value: mixed) {
//可传入任意数据类型,不能进行隐式类型转换。 用if , else 判断
}
function passAny (value: any) {
// 可传入任意数据类型,可以当做任意数据任性使用, 隐式类型转换
}
Flow 运行环境限制
const element:HTMLElement | null = document.getElementById('app')