javascript - how to declare that a given class implements an interface in Facebook Flow? -
i have following code using flow:
// @flow 'use strict'; import assert 'assert'; declare interface ipoint { x: number; y: number; distanceto(other: ipoint): number; } class point { x: number; y: number; distanceto(a: ipoint): number { return distance(this, a); } constructor(x: number, y: number) { this.x = x; this.y = y; } } function distance(p1: ipoint, p2: ipoint): number { function sq(x: number): number { return x*x; } return math.sqrt( sq(p2.x-p1.x)+sq(p2.y-p1.y) ); } assert(distance ( new point(0,0), new point(3,4))===5); // distance ( new point(3,3), 3); // flow complains, expected assert((new point(0,1)).distanceto(new point(3,5))===5); // (new point(0,1)).distanceto(3); // flow complains expected
running npm run flow
yields no complains expected, whereas commented-out lines give rise warnings (again, expected).
so all's world except don't know how make explicit @ point class point
defined "implementing" interface ipoint
. there way or not idiomatic?
here simplest way it:
class point { x: number; y: number; constructor(x: number, y: number) { (this: ipoint); this.x = x; this.y = y; } }
the key part (this: ipoint)
. js vm's point of view it's expression nothing, flow needs check if casting this
ipoint
valid, checking if class implements ipoint
interface.
Comments
Post a Comment