2016-01-21 47 views
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 
} 

回答

3

我如何強制型,或使這項工作反正...

使用類型斷言:

// If first is Point all must be Points 
let points = pointsOrWalls as Point[]; 

完成:

class Wall {w} 
class Point {p} 

class Foo { 
    walls; 
    name 
    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 
      let points = pointsOrWalls as Point[]; 

      // But here typescript says that pointsOrWalls is of type (Wall | Point)[] 
      this.walls = points.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 
    } 
} 

更多

https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

+0

雖然這很好,有沒有辦法不重新聲明變量? – Akxe

+0

你可以創建一個用戶自定義類型的後衛 – basarat

+0

不明白,有什麼防範? – Akxe