在Flow中,为什么要使用类而不是类型?
type Point = {x: number; y: number};
class Point = {x: number; y: number};
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您只需要一种类型.
但是如果你想定义方法,你会想要使用一个类.
class Point {
x: number;
y: number;
constructor(x, y) {this.x = x; this.y = y;}
distance_from_origin(): number { /* code goes here */ }
angle_from_origin(): number { /* code goes here */ }
}
p: Point = new Point(2, 3);
d = p.distance_from_origin()
Run Code Online (Sandbox Code Playgroud)
类型是编译时检查的流程功能,可帮助您捕获代码中的错误.在运行之前,它们完全从代码中删除.
类根本不是Flow特性(尽管Flow理解类 - 您创建的每个类也定义了Flow类型) - 它们是ES6的一个特性,即下一版本的JavaScript.Babel,从代码中剥离Flow类型以使其成为有效JavaScript的程序,也可以将类转换为ES5兼容代码.
| 归档时间: |
|
| 查看次数: |
3049 次 |
| 最近记录: |