看一段常见代码
function foo(x) { return x + 10 } foo('Hello!')上述的函数传参肯定不是我们希望的,因为JavaScript 是一门动态类型语言,变量和参数的类型是可以随时改变的,这样会提高在运行时产生错误的概率。但是怎么去避免这样的错误呢?
如何对一个文件进行类型检查?
// @flow // 或者下面这种 /* @flow */JavaScript 中的基本类型,类型标注语法是在变量后加上一个冒号,空格,然后是相应的类型名称,如:
// @flow const a: string = 'zhihu' const b: number = 5 const c: boolean = false const d: void = undefined const e: null = null以上需要注意的几点:
undefined 的类型是 void;null 的类型是 null;string 类型、number 类型和 boolean 类型,其类型名称都是小写开头;但是在 JS 中还有相对应的大写开头的类型名称,如 String,Number, Boolean;对函数类型我们主要是标注其接受的参数类型和返回值类型;下面的示例中分别展示了如何对函数声明、函数表达式,以及箭头函数加上类型标注。
// @flow // 函数声明 function getLength(str: string): number { return str.length } // 函数表达式 const greeting = function(welcome: string): void { console.log(welcome) } // 箭头函数 const addNumber = (a: number, b: number): number => a + b对数组的标注 Flow 提供两种语法,
Array 后接一对尖括号,且尖括号里边就是数组项的类型名称;类型名称后加一对中括号。 // @flow const names: Array<string> = ['a', 'b', 'c'] const ages: number[] = [1, 2, 3, 4]另外一种常见的数组是元组(Tuple)。在其他语言里,元组可能是一个特定的类型结构;但是在 JS 里,元组就是数组来表示的,并且是一个有限数组,数组每一项的类型分别标注出来。
// @flow const recordItem: [number, string, boolean] = [1, 'First', true]对对象类型加上类型标注的方式是定义其结构(Shape),即有哪些属性,属性及属性值的类型;
// @flow type BorderConfigType = { width: number, color: string, hasShadow: boolean } const borderConfig: BorderConfigType = { width: 10, color: 'red', hasShadow: true }type 是 Flow 中的关键字,用来定义自定义的类型,并且可以在后面的类型标注中使用。例如:
// @flow type StringType = string; const name: StringType = ‘zhihu’; type TupleType = [ number, string ] const record: TupleType = [ 1, ‘a’ ]Flow 支持对 ES6 中的类进行类型标注:包括类的属性和方法;类中用到的属性必须额外添加类型标注,并且是在与方法同一个层级(而不是在方法体内部)。
// @flow class WrongClass1{ method(){ this.props = 1; // Flow 会报错,因为没有对 props 进行类型标注 } } class WrongClass2{ method(){ this.props: number = 1; // Flow 还是会报错,对属性的类型标注必须与方法同一个层级 } } class RightClass { props: number; // 对,就像这样。 method(){ this.props = 1; } } class MyClass{} const mc: MyClass = new MyClass();