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

Mar*_*tus 2 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
Run Code Online (Sandbox Code Playgroud)

运行npm run flow产生没有预期的抱怨,而注释掉的线引起警告(再次,如预期).

所以,除了我不知道如何在Point定义类是"实现"接口的那一点上使它显式化之外,所有这些都与世界很好IPoint.有没有办法这样做或者不是惯用的?

vku*_*kin 5

这是最简单的方法:

class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        (this: IPoint);
        this.x = x;
        this.y = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

关键部分是(this: IPoint).从JS VM的角度来看,它只是一个什么也不做的表情,但流量需要检查,如果铸造thisIPoint是否有效,如果类实现有效检查IPoint接口.