有什么方法可以指定自己的类型吗?或解决方法“属性类型不兼容。”

时间:2016-03-08 22:59:03

标签: javascript typescript

我有两个班级,LineWall。行类是父类,collide函数只接受行数组,只返回过滤回来 Wall类也是这样,但对于Walls来说。

class Line {
    public start: Point
    public end: Point

    constructor(start: Point, end: Point) {
        this.start = start
        this.end = end
    }

    collide(lines: Line[]):Line[] {
        return lines.filter((line) => {return true || false})
    }
}

和华尔班:

class Wall extends Line {
    public start: Point
    public end: Point
    public thickness: number

    private collideWith: Wall[]

    constructor(start: Point, end: Point,thickness: number) {
        super(start,end)
        this.thickness = thickness
    }

    collide(walls: Wall[]):Wall[] {
        return this.collideWith = walls.filter((wall) => {return true || false})
        // I would love if this could return just void
        // since it update private property only,
        // but returning Wall[] works too
    }
}

此代码产生错误:

file.ts(line,7): error TS2415: Class 'Wall' incorrectly extends base class 'Line'.
Types of property 'collide' are incompatible.
    Type '(walls: Wall[]) => void' is not assignable to type '(lines: Line[]) => Line[]'.
      Types of parameters 'walls' and 'lines' are incompatible.
        Type 'Wall[]' is not assignable to type 'Line[]'.
          Type 'Wall' is not assignable to type 'Line'.
            Types of property 'collide' are incompatible.
              Type '(walls: Wall[]) => void' is not assignable to type '(lines: Line[]) => Line[]'.
                Types of parameters 'walls' and 'lines' are incompatible.
                  Type 'Wall[]' is not assignable to type 'Line[]'.
                    Type 'Wall' is not assignable to type 'Line'.

如何处理这种情况?

1 个答案:

答案 0 :(得分:1)

从你的代码:

    // I would love if this could return just void
    // since it update private property only,
    // but returning Wall[] works too

要使子类返回void,父类也必须返回void。这是因为OO多态性。考虑一下:

var foo:Line;
var bar: Wall;
foo = bar; // polymorphism. After all `Wall` is just `Line` with other stuff
var x = foo.collide(); // Actually calls `bar.collide`. So signatures must be compatible. 

更新(使用self[]类型):

在TypeScript中称为this类型。这是一个示例:

interface Point {x:number,y:number}

class Line {
    public start: Point
    public end: Point

    constructor(start: Point, end: Point) {
        this.start = start
        this.end = end
    }

    collide(lines: this[]) {
        return lines.filter((line) => {return true || false});
    }
}

class Wall extends Line {
    public start: Point
    public end: Point
    public thickness: number

    private collideWith: Wall[]

    constructor(start: Point, end: Point,thickness: number) {
        super(start,end)
        this.thickness = thickness
    }

    collide(walls: this[]) {
        return this.collideWith = walls.filter((wall) => {return true || false});
    }
}