我有两个类,Line
和 Wall
。 Line 类是父类,并且具有仅接受 Lines 数组的 collide
函数,并且仅将其过滤回来。
Wall 类执行相同的操作,但针对的是 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'.
遇到这种情况该如何处理?
最佳答案
来自您的代码:
// 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});
}
}
关于javascript - 有什么办法可以为自己指定类型吗?或者解决方法 "Types of property are incompatible.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879735/