JYL
JYL

Reputation: 8319

TypeScript definition : same name but different types inside and outside module?

I'm trying to build the typescript definition file for this code (in myscript.ts) :

var rectangle = new Rectangle(new Point(20, 20), new Size(60, 60));
var path = new Path.Rectangle(rectangle);
path.strokeColor = 'black';

Please note that here first Rectangle is a different type from the second (Path.Rectangle).

This is what I have for now (in myscript.d.ts) :

declare class Point {
    constructor(x: number, y: number);
    add: (something: number[]) => Point;
}
declare class Size {
    constructor(width: number, height: number);
}
declare class Rectangle {
    constructor(point: Point, size: Size);
    topLeft: Point;
    bottomRight: Point;
}
declare module Path {
    class PathBase {
        strokeColor: string;
        bounds: Rectangle; // <== here I need the Rectangle type defined outside of the Path module
        fillColor: Color;
    }

    export class Rectangle extends PathBase {
        constructor(point: Point, size: Size);
        constructor(rec : Rectangle); // <== here I need the Rectangle type defined outside of the Path module
    }
}

With this definition, both of the following lines failed :

var path = new Path.Rectangle(rectangle);
var upperLeft = path.bounds.topLeft;

I understand why but don't know how to fix the definition. Thanks for your help.

Upvotes: 3

Views: 1848

Answers (1)

JYL
JYL

Reputation: 8319

Based on @xmojmr comment, I found a valid definition :

My first attempt :

declare class Rectangle {
    constructor(point: Point, size: Size);
    topLeft: Point;
    bottomRight: Point;
}

becomes :

declare class NumericRectangle { // <=================== renamed
    constructor(point: Point, size: Size);
    topLeft: Point;
    bottomRight: Point;
}

declare class Rectangle extends NumericRectangle {  // <=================== added
}

... and

declare module Path {
    class PathBase {
        strokeColor: string;
        bounds: Rectangle; // <== here I need the Rectangle type defined outside of the Path module
        fillColor: Color;
    }

    export class Rectangle extends PathBase {
        constructor(point: Point, size: Size);
        constructor(rec : Rectangle); // <== here I need the Rectangle type defined outside of the Path module
    }
}

... becomes :

declare module Path {
    class PathBase {
        strokeColor: string;
        bounds: NumericRectangle;  // <=================== modified
        fillColor: Color;
    }

    export class Rectangle extends PathBase {
        constructor(point: Point, size: Size);
        constructor(rec: NumericRectangle); // <=================== modified
    }
}

Upvotes: 2

Related Questions