string = tuple[n];
// ...
}
tuple类型的长度一定要严格等于你声明时候的长度
tuple 不能匹配 数组类型, 这也是他们的差别
tuple 只能用 array 的 join() 方法 其他的都不可以用,否则报错
class type
javascript 的class 再flow 可以是值 也可以是类型
class MyClass {
// ...
}
let myInstance: MyClass = new MyClass();class 里的字段一定要声明类型了才可以用
// @flow
class MyClass {
prop: number;// 如果没有这行, 下的赋值会报错,因为prop 没确定类型
method() {
this.prop = 42;
}
}再外部使用的字段,必须要再class 的块里面声明一次
// @flow
function func_we_use_everywhere (x: number): number {
return x + 1;
}
class MyClass {
static constant: number; // 内部声明
static helper: (number) => number;
method: number => number;
}
MyClass.helper = func_we_use_everywhere
MyClass.constant = 42 // 外部使用
MyClass.prototype.method = func_we_use_everywhere声明并且赋值的语法
class MyClass {
prop: number = 42;
}类的泛型
class MyClass<A, B, C> {
property: A;
method(val: B): C {
// ...
}
}如果你要把class作为一个类型,你声明了几个泛型, 你就要传几个参数
// @flow
class MyClass<A, B, C> {
constructor(arg1: A, arg2: B, arg3: C) {
// ...
}
}
var val: MyClass<number, boolean, string> = new MyClass(1, true, 'three');别名类型(type aliases)
跟上面提到的 type 关键字一样
// @flow
type MyObject = {
foo: number,
bar: boolean,
baz: string,
};这个是类型别名 可以在不同的地方复用
// @flow
type MyObject = {
// ...
};
var val: MyObject = { /* ... */ };
function method(val: MyObject) { /* ... */ }
class Foo { constructor(val: MyObject) { /* ... */ } }别名泛型
type MyObject<A, B, C> = {
property: A,
method(val: B): C,
};别名泛型是参数化的,也就是你用了以后, 你声明的所有参数 你全部都要传
// @flow
type MyObject<A, B, C> = {
foo: A,
bar: B,
baz: C,
};
var val: MyObject<number, boolean, string> = {
foo: 1,
bar: true,
baz: 'three',
};不透明的类型别名(opaque type aliases)
通过类型系统的加强抽象
不透明类型别名是不允许访问定义在文件之外的的基础类型的类型别名.
opaque type ID = string; // 一个新的关键字 并且这是声明一个不透明类型别名的语法不透明类型别名可以复用
// @flow
// 在这个例子,我理解的是 外部只能访问到这个文件的ID 类型, 并不能访问到这个文件里面的string 基础类型. 这就是不透明的类型别名
opaque type ID = string;
function identity(x: ID): ID {
return x;
}
export type {ID};你可以可选的加一个子类型约束
在一个 不透明的类型别名
的类型后面
opaque type Alias: SuperType = Type;任何类型都可以作为父类型 或者 不透明的类型别名
的类型
opaque type StringAlias = string;
opaque type ObjectAlias = {
property: string,
method(): number,
};
opaque type UnionAlias = 1 关键词:javascript静态分类如何解析flow的用法(详细)