Akxe
Akxe

Reputation: 11575

Type problems while overloading constructors

I am having problems while overloading constructors, it won't let me tell it what type is what the variable contains. How can I force a type, or make this work anyway...?

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
}

Upvotes: 0

Views: 45

Answers (1)

basarat
basarat

Reputation: 276125

How can I force a type, or make this work anyway...

Use a type assertion:

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

Complete:

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
    }   
}

More

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

Upvotes: 3

Related Questions