0

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
}

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

Although this is good, is there any way to not re-declare variable?
You can create a user defined type guard
Don't understand, what guard?
@Akxe I just wrote docs for your : basarat.gitbooks.io/typescript/content/docs/types/… 🌹
Thank you so much, this is definitely worth being in bookmarks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.