2014-12-02 167 views
3

我試圖建立該代碼打字稿定義文件(myscript.ts):TypeScript定義:模塊內部和外部的名稱相同但名稱不同?

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

請注意,這裏第一個矩形是從第二(Path.Rectangle)不同的類型。

這是我現在(在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 
    } 
} 

根據這個定義,無論是以下行的失敗:

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

我明白爲什麼,但不知道如何修復定義。謝謝你的幫助。

+0

如果我是你,我會更改名稱,不確定是否有其他解決方案。 – 2014-12-02 15:33:47

+0

@Omri:我無法更改名稱,因爲代碼來自外部lib:paperjs。實際上,原始代碼來自這裏:http://paper.jp/reference/path/#path-rectangle-rectangle – JYL 2014-12-02 16:02:12

+2

也許有沒有簡單而好的方法,但你應該能夠通過聲明一個假名稱來解決它別名(例如'declare interface __r extends Rectangle {}'並使用別名'__r'而不是全局範圍'Rectangle',類似於[Stack Overflow:與接口同名的TypeScript類中使用的方式](http:/ /stackoverflow.com/questions/26591245/typescript-class-with-same-name-as-interface) – xmojmr 2014-12-02 17:00:43

回答

2

基於@xmojmr評論,我發現了一個有效的定義:

我第一次嘗試:

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

變爲:

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

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

...和

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

...變成:

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 
    } 
} 
相關問題