如何声明给定的类在Facebook Flow中实现接口?

时间:2016-07-06 12:01:57

标签: javascript node.js flowtype

我使用Flow有以下代码:

// @flow    
'use strict';

import assert from '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, as expected
assert((new Point(0,1)).distanceTo(new Point(3,5))===5);
// (new Point(0,1)).distanceTo(3); // Flow complains as expected

运行npm run flow不会产生预期的抱怨,而注释掉的行会引发警告(再次,如预期的那样)。

所以,除了我不知道如何在定义类Point以确保它是"实现"界面IPoint。有没有办法这样做或者不是惯用的?

3 个答案:

答案 0 :(得分:5)

这是最简单的方法:

API_RESPONSE_ARRAY = responseJSON.result.items.map((item) => item.name);

关键部分是class Point { x: number; y: number; constructor(x: number, y: number) { (this: IPoint); this.x = x; this.y = y; } } 。从JS VM的角度来看,它只是一个什么都不做的表达式,但Flow需要检查转换(this: IPoint)this是否有效,有效地检查类是否实现了IPoint接口。

答案 1 :(得分:2)

另一种简单的方法是:

interface IPoint { ... }
class Point { ... }

(Point: Class<IPoint>); // checks that Point is a class that implements IPoint

答案 2 :(得分:0)

0.57.3开始(很可能更早)可以做到:

class Point implements IPoint {
... // rest of class definition
}
相关问题