我有两个类,Line
和Wall
。线类是父类,并具有只接受线阵列的函数,并且只返回它过滤的结果。
墙上的课程也是如此,但对于墙壁来说。任何方式指定类型自我?或解决方法“属性类型不兼容”。
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'.
如何应对这种情况?
它为我编译,你有什么tsc版本?尝试升级你的tsc – dannielum
@dannielum我使用崇高的文本来编译它,它应该使用npm中的一个。输入“npm v tsc”后,我得到:版本:'1.20150623.0'(多行之一) – Akxe
@dannielum和'npm view typescript version'返回1.8.7 – Akxe