0
我在重載構造函數時遇到問題,它不會讓我告訴它變量包含的是什麼類型。我如何強制類型,或無論如何做這個工作......?重載構造函數時出現類型問題
constructor(points: Point[], name?: string);
constructor(walls: Wall[], name?: string);
constructor(pointsOrWalls: (Wall | Point)[], name?: string) {
if (pointsOrWalls[0] instanceof Point) {
// If first is Point all must be Points
// But here typescript says that pointsOrWalls is of type (Wall | Point)[]
this.walls = pointsOrWalls.map(function(point, ind, points) {
return new Wall(point, points[++ind % points.length])
})
}else{
// Since these aren't points they are Walls
this.walls = walls
}
this.name = name
}
雖然這很好,有沒有辦法不重新聲明變量? – Akxe
你可以創建一個用戶自定義類型的後衛 – basarat
不明白,有什麼防範? – Akxe