简体   繁体   English

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

[英]how to declare that a given class implements an interface in Facebook Flow?

I have the following code using Flow: 我使用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

Running npm run flow yields no complains as expected, whereas the commented-out lines give rise to warnings (again, as expected). 运行npm run flow不会产生预期的抱怨,而注释掉的行会引发警告(同样,如预期的那样)。

So all's well with the world except that I don't know how to make it explicit at the point where class Point is defined that it is "implementing" interface IPoint . 所以除了我不知道如何在类Point定义它是“实现”接口IPoint时明确如何使它明确,所以一切都很好。 Is there a way to do so or is it not idiomatic? 有没有办法这样做或者不是惯用的?

Here is the simplest way to do it: 这是最简单的方法:

class Point {
    x: number;
    y: number;
    constructor(x: number, y: number) {
        (this: IPoint);
        this.x = x;
        this.y = y;
    }
}

The key part is (this: IPoint) . 关键部分是(this: IPoint) From JS VM's point of view it's just an expression that does nothing, but Flow needs to check if casting this to IPoint is valid, effectively checking if class implements IPoint interface. 从JS VM的角度来看,它只是一个什么都不做的表达式,但Flow需要检查是否thisIPoint是有效的,有效地检查类是否实现了IPoint接口。

Another easy way to do it is: 另一个简单的方法是:

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

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

As of 0.57.3 (and quite possibly earlier) one can do: 0.57.3 (可能更早)可以做到:

class Point implements IPoint {
... // rest of class definition
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM