Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class vs type in Flow

Tags:

flowtype

In Flow, why would one use a class versus a type?

type Point = {x: number; y: number};
class Point = {x: number; y: number};
like image 961
Dave Ford Avatar asked Oct 14 '16 14:10

Dave Ford


1 Answers

In your example, a type is all you need.

But if you want to define methods, you'll want to use a class.

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()

Types are a flow features for compile-time checking, to help you catch errors in your code. They are entirely stripped from the code before running it.

Classes aren't a Flow feature at all (Although Flow understands classes - every class you create also defines a Flow type) - they're a feature of ES6, the next version of JavaScript. Babel, the same program that strips Flow types from your code to make it valid JavaScript, can also convert your classes to ES5-compatible code.

like image 120
Josh Avatar answered Oct 02 '22 20:10

Josh